java浏览器

来源:互联网 发布:mac修容日上价格 编辑:程序博客网 时间:2024/04/29 16:34

用java写的个浏览器的原代码
下载后可以直接编译通过
这个浏览器现在还不支持css
还有收藏夹功能本人还不会实现
希望大家能帮我修改和改进..
给本人一些指点,
本人qq:17708656 身份认证:java学习
希望认识一些学习java和对其感兴趣的朋友,一起学习!!!!!!

 /**
 * @(#)WebBrowser.java
 *
 *
 * @author
 * @version 1.00 2007/4/28
 */
 import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.MouseListener;
import java.awt.*;
import javax.swing.*;
import javax.swing.text.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileView;
import java.io.*;
import java.net.*;
import java.util.*;

public class WebBrowser extends JFrame implements HyperlinkListener,ActionListener{
       
    /**
     * Creates a new instance of <code>WebBrowser</code>.
     */
    //.......
   


   
    //.........
    
   //建立主件
  
   JToolBar bar =new JToolBar();//工具栏
  
  
   JTextField jurl=new JTextField(60);//地址栏
   JTextField jurlSource=new JTextField(60);//地址栏
   JEditorPane2 jEditorPane1=new JEditorPane2();//网页框
   JScrollPane scrollPane=new JScrollPane(jEditorPane1);//滚动条
   JFileChooser chooser=new JFileChooser();
   JFileChooser chooser1=new JFileChooser();//选择文件
   String htmlSource;
   JWindow window=new JWindow(WebBrowser.this);//使用指定的所有者框架创建窗口
  
   JButton button2=new JButton("go back");
   Toolkit toolkit=Toolkit.getDefaultToolkit();//获取默认工具包
  
   JMenuBar jMenuBar1=new JMenuBar();//建立菜单栏
  
   JMenu fileMenu=new JMenu("File(F)");//建立菜单组
   JMenuItem saveAsItem=new JMenuItem("save As(S)");
   JMenuItem exitItem=new JMenuItem("exit(E)");
  
   JMenu bookMarkMenu=new JMenu("bookMark(B)");//建立菜单组
   JMenuItem saveBookMarkItem=new JMenuItem("save bookmark(K)");
  
   JMenu editMenu=new JMenu("Edit(E)");//建立菜单组
   JMenuItem backItem=new JMenuItem("Back(Z)");
   JMenuItem forwardItem=new JMenuItem("Forward(P)");
  
   JMenu viewMenu=new JMenu("View(V)");//建立菜单组
   JMenuItem fullscreenItem=new JMenuItem("fullscreen(U)");
   JMenuItem sourceItem=new JMenuItem("source(C)");
   JMenuItem reloadItem=new JMenuItem("reload(R)");
  
   JToolBar toolBar=new JToolBar();
   JButton picSave=new JButton("save as");
   JButton picBack=new JButton("back");
   JButton picForward=new JButton("forward");
   JButton picView=new JButton("source");
   JButton picExit=new JButton("exit");
   //建立工具栏
  
  
   JLabel label=new JLabel("Adress");
   JButton button=new JButton("GO");
  
   JLabel labelSource=new JLabel("View Source");
   JButton buttonSource=new JButton("View");
  
   Box adress=Box.createHorizontalBox();  //创建一个从左到右显示其组件
   Box adressSource=Box.createHorizontalBox();
   private ArrayList history=new ArrayList();
   private int historyIndex;
  
  
  
  
  
    public WebBrowser() {
     
     
     setTitle("network by liujia");
     setResizable(false);//设置此 frame 是否可由用户调整大小
     
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   
     jEditorPane1.addHyperlinkListener(this);//事件监听
     
     
     bookMarkMenu.setMnemonic('B');
     saveBookMarkItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K,InputEvent.CTRL_MASK));
     fileMenu.setMnemonic('F');
     saveAsItem.setMnemonic('S');
        saveAsItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S,InputEvent.CTRL_MASK));
     exitItem.setMnemonic('P');
     exitItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_E,InputEvent.CTRL_MASK));
     //设置热键
     
     fileMenu.add(saveAsItem);
     fileMenu.addSeparator();
     fileMenu.add(exitItem);
     
     backItem.setMnemonic('B');
     backItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Z,InputEvent.CTRL_MASK));
     forwardItem.setMnemonic('D');
     forwardItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_P,InputEvent.CTRL_MASK));
     editMenu.setMnemonic('E');
     editMenu.add(backItem);
     editMenu.addSeparator();
     editMenu.add(forwardItem);
     
     viewMenu.setMnemonic('V');
     fullscreenItem.setMnemonic('U');
     fullscreenItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_U,InputEvent.CTRL_MASK));
     sourceItem.setMnemonic('C');
     sourceItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,InputEvent.CTRL_MASK));
     reloadItem.setMnemonic('R');
     reloadItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,InputEvent.CTRL_MASK));
     
     Container contentPane=getContentPane();
     scrollPane.setPreferredSize(new Dimension(100,500));
     contentPane.add(scrollPane,BorderLayout.SOUTH);
     
     adressSource.add(labelSource);
     adressSource.add(jurlSource);
     adressSource.add(buttonSource);
     
     
     toolBar.add(picSave);
     toolBar.addSeparator();
     toolBar.add(picBack);
     toolBar.addSeparator();
     toolBar.add(picForward);
     toolBar.addSeparator();
     toolBar.add(picView);
     toolBar.addSeparator();
     toolBar.add(picExit);
     toolBar.addSeparator();
     toolBar.add(picExit);
     toolBar.addSeparator();
     
     toolBar.add(adressSource);
     
     contentPane.add(bar,BorderLayout.CENTER);
     contentPane.add(toolBar,BorderLayout.NORTH);
     
     viewMenu.add(fullscreenItem);
     viewMenu.addSeparator();
     viewMenu.add(sourceItem);
     viewMenu.addSeparator();
     viewMenu.add(reloadItem);
     
     bookMarkMenu.add(saveBookMarkItem);
     
     
     jMenuBar1.add(fileMenu);
     jMenuBar1.add(editMenu);
     jMenuBar1.add(viewMenu);
     jMenuBar1.add(bookMarkMenu);
     
     setJMenuBar(jMenuBar1);
     
     adress.add(label);
     adress.add(jurl);
     adress.add(button);
     bar.add(adress);
     
     
     saveAsItem.addActionListener(this);
     picSave.addActionListener(this);
     exitItem.addActionListener(this);
     picExit.addActionListener(this);
     backItem.addActionListener(this);
     picBack.addActionListener(this);
     forwardItem.addActionListener(this);
     picForward.addActionListener(this);
     fullscreenItem.addActionListener(this);
   
     sourceItem.addActionListener(this);
     picView.addActionListener(this);
     reloadItem.addActionListener(this);
     button.addActionListener(this);
     buttonSource.addActionListener(this);
     jurl.addActionListener(this);
     jurlSource.addActionListener(this); 
     saveBookMarkItem.addActionListener(this);
     
   
     
     
    }
   //..................
   
    //.....
   
     public void actionPerformed(ActionEvent e)
     {
     
     String url="";
     if(e.getSource()==button){ //按down.................................................
      url=jurl.getText();
      if(url.length()>0&&url.startsWith("http://")){
       try{
        jEditorPane1.setPage(url);
        history.add(url);
        historyIndex=history.size()-1;// 返回此列表中的元素数
        jEditorPane1.setEditable(false);
        jEditorPane1.revalidate();
        }
        catch(Exception ex){
         JOptionPane.showMessageDialog(WebBrowser.this,"don't open the search page","network",JOptionPane.ERROR_MESSAGE);
         }
       }
       else if(url.length()>0&&!url.startsWith("http://")){
        url="http://"+url;
        try{
         jEditorPane1.setPage(url);
            history.add(url);
            historyIndex=history.size()-1;// 返回此列表中的元素数
            jEditorPane1.setEditable(false);
            jEditorPane1.revalidate();
         }
          catch(Exception ex){
         JOptionPane.showMessageDialog(WebBrowser.this,"don't open the search page","network by liujia",JOptionPane.ERROR_MESSAGE);
         } 
        }
           else if(url.length()==0){
              JOptionPane.showMessageDialog(WebBrowser.this,"don't open the search page","network by liujia",JOptionPane.ERROR_MESSAGE);
         
            }
      }
      //............按回车
      else if(e.getSource()==jurl){
          url=jurl.getText();
         
          if(url.length()>0&&url.startsWith("http://")){
       try{
        jEditorPane1.setPage(url);
        history.add(url);
        historyIndex=history.size()-1;// 返回此列表中的元素数
        jEditorPane1.setEditable(false);
        jEditorPane1.revalidate();
        jurl.setMaximumSize(jurl.getPreferredSize());
        }
        catch(Exception ex){
         JOptionPane.showMessageDialog(WebBrowser.this,"don't open the search page","network by liujia",JOptionPane.ERROR_MESSAGE);
         }
           }
           
          else if(url.length()>0&&!url.startsWith("http://")){
        url="http://"+url;
        try{
         jEditorPane1.setPage(url);
            history.add(url);
            historyIndex=history.size()-1;// 返回此列表中的元素数
            jEditorPane1.setEditable(false);
            jEditorPane1.revalidate();
         }
          catch(Exception ex){
         JOptionPane.showMessageDialog(WebBrowser.this,"don't open the search page","network by liujia",JOptionPane.ERROR_MESSAGE);
         } 
        }
           else if(url.length()==0){
              JOptionPane.showMessageDialog(WebBrowser.this,"don't open the search page","network by liujia",JOptionPane.ERROR_MESSAGE);
         
            }
       
       
       }
       
       //..................................另存为
       
       else if(e.getSource()==picSave||e.getSource()==saveAsItem){
           url=jurl.getText().trim();//去掉字符串头和尾的空格
           if(url.length()>0&&!url.startsWith("http://")){
             url="http://"+url;
          
            }
            if(!url.equals("")){
              saveFile(url);
             }
             else{
               JOptionPane.showMessageDialog(WebBrowser.this,"please input url's adress","network by lijia",JOptionPane.ERROR_MESSAGE);
        
              }
        } 
       
     //exit...
     else if(e.getSource()==exitItem||e.getSource()==picExit){
      System.exit(0);
      }
      
     //back.
     else if(e.getSource()==backItem||e.getSource()==picBack){
      
       historyIndex--;
       if(historyIndex<0)
        historyIndex=0;
        url=jurl.getText();
        try{
         url=(String)history.get(historyIndex);
         jEditorPane1.setPage(url);
         jurl.setText(url.toString());
         jEditorPane1.setEditable(false);
         jEditorPane1.revalidate();
         /**
          *public void revalidate()支持推迟的自动布局。
调用 invalidate 并将此组件的 validateRoot 添加到需要验证的组件列表中。调度完当前所有未完成的事件后进行验证。换句话说,调用此方法后,将验证浏览此组件的包含层次结构时找到的第一个 validateRoot(如果有)。默认情况下,JRootPane、JScrollPane 和 JTextField 从 isValidateRoot 返回 true。

当属性值更改,从而影响此组件的大小、位置或内部布局时,就对此组件自动调用此方法。这种自动更新不同于 AWT,因为通常来说,程序不再需要调用 validate 来获得要更新的 GUI 的内容。

          *
          **/
         }
       catch(Exception ex){
        
        }
      }
      
      //forworad..... 
     else if(e.getSource()==forwardItem||e.getSource()==picForward){
       historyIndex++;
       if(historyIndex>=history.size())
        historyIndex=history.size()-1;
        url=jurl.getText();
        try{
           url=(String)history.get(historyIndex);
           jEditorPane1.setPage(url);
           jurl.setText(url.toString());
              jEditorPane1.setEditable(false);
           jEditorPane1.revalidate();
         }
         catch(Exception ex){
          }
      
      } 
       
     //fullscreen
     else if(e.getSource()==fullscreenItem){
        boolean add_button2=true;
       
      } 
       
       
       
     //查看原文件  
     else if(e.getSource()==sourceItem||e.getSource()==picView){
      url=jurl.getText().toString().trim();
      if(url.length()>0&&!url.startsWith("http://")){
       url="http://"+url;
       }
       if(!url.equals("")){
         getHtmlSource(url);
         ViewSourceFrame vsframe=new ViewSourceFrame(htmlSource);
         vsframe.setBounds(0,0,800,500);
         vsframe.setVisible(true);
        }
       else{
         JOptionPane.showMessageDialog(WebBrowser.this,"please input url's adress","network by lijia",JOptionPane.ERROR_MESSAGE);
        
        }
      } 
       
     //查看网页原代码
     
      else if(e.getSource()==buttonSource||e.getSource()==jurlSource){
      url=jurlSource.getText().toString().trim();
      if(url.length()>0&&!url.startsWith("http://")){
       url="http://"+url;
       }
       if(!url.equals("")){
         getHtmlSource(url);
         ViewSourceFrame vsframeSource=new ViewSourceFrame(htmlSource);
         vsframeSource.setBounds(0,0,800,500);
         vsframeSource.setVisible(true);
        }
       else{
         JOptionPane.showMessageDialog(WebBrowser.this,"please input url's adress","network by lijia",JOptionPane.ERROR_MESSAGE);
        
        }
      } 
       //....................收藏夹
      else if(e.getSource()==saveBookMarkItem){
          
       
       }
       //................
      
      //刷新
      else if(e.getSource()==reloadItem){
         url=jurl.getText();
         if(url.length()>0&&url.startsWith("http://")){
            try{
               jEditorPane1.setPage(url);
               jEditorPane1.setEditable(false);
               jEditorPane1.revalidate();
             }
             
             catch(Exception ex){
              }
              
       
          }
          
          
          else if(url.length()>0&&!url.startsWith("http://")){
            url="http://"+url;
            try{
              jEditorPane1.setPage(url);
                  jEditorPane1.setEditable(false);
                  jEditorPane1.revalidate();
             }
             catch(Exception ex){
              }
           }
       }  
     }
     //.............savefile
     void saveFile(final String url){
        final String linesep=System.getProperty("line.separator");//获得指定键指示的系统属性
        chooser1.setCurrentDirectory(new File("."));//设置当前目录
        chooser1.setDialogType(JFileChooser.SAVE_DIALOG);//设置此对话框的类型,||指示 JFileChooser 支持 "Save" 文件操作的类型值
        chooser1.setDialogTitle("Save as..");//设置显示在 JFileChooser 窗口标题栏的字符串
        if(chooser1.showSaveDialog(this)!=JFileChooser.APPROVE_OPTION)// 弹出一个 "Save File" 文件选择器对话框||选择确认(yes、ok)后返回该值
         return;
         this.repaint();
         Thread thread=new Thread(){
           public void run(){
            try{
             java.net.URL source=new URL(url);
             InputStream in=new BufferedInputStream(source.openStream());//
             BufferedReader br=new BufferedReader(new InputStreamReader(in));
             File fileName=chooser1.getSelectedFile();//返回选中的文件
             FileWriter out=new FileWriter(fileName);
             BufferedWriter bw=new BufferedWriter(out);
             String line;
             while((line=br.readLine())!=null){
              bw.write(line);
              bw.newLine();//写入一个行分隔符
              }
              
             bw.flush();
             bw.close();
             out.close();
             String dMessage=url+" had saved to"+linesep+fileName.getAbsolutePath();//返回抽象路径名的绝对路径名字符串
             String dTitle="Save as";
             int dType=JOptionPane.INFORMATION_MESSAGE;
             JOptionPane.showMessageDialog((Component)null,dMessage,dTitle,dType);
             }
            catch(java.net.MalformedURLException muex){
             JOptionPane.showMessageDialog((Component)null,muex.toString(),"network by liujia",JOptionPane.ERROR_MESSAGE);
             }
            catch(Exception ex){
             JOptionPane.showMessageDialog((Component)null,ex.toString(),"network by liujia",JOptionPane.ERROR_MESSAGE);
             
             
                 }  
             
             }
            
            };
            thread.start();
          
          
      
      }
     //....................
     
     //getsource
     void getHtmlSource (String url){
       String linesep,htmlLine;
       linesep=System.getProperty("line.separator");
       htmlSource="";
       try{
        java.net.URL source =new URL(url);
        InputStream in=new BufferedInputStream(source.openStream());
        BufferedReader br=new BufferedReader(new InputStreamReader(in));
        while((htmlLine=br.readLine())!=null){
         htmlSource=htmlSource+htmlLine+linesep;
         }
        
        }
       catch(java.net.MalformedURLException muex){
          JOptionPane.showMessageDialog(WebBrowser.this,muex.toString(),"network by liujia",JOptionPane.ERROR_MESSAGE);
        }
        
       catch(Exception e){
        JOptionPane.showMessageDialog(WebBrowser.this,e.toString(),"network by liujia",JOptionPane.ERROR_MESSAGE);
        
        }
      
      }
    //............
     public void hyperlinkUpdate(HyperlinkEvent e)
     
     {
      try{
       if(e.getEventType()==HyperlinkEvent.EventType.ACTIVATED)
        
        
        jEditorPane1.setPage(e.getURL());
        jurl.setText(e.getURL().toString());
        history.add(e.getURL().toString());
        historyIndex=history.size()-1;
        
        
       }
      catch(Exception ex){
       ex.printStackTrace(System.err);
       }
     }
   
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
       
        try {
         
         UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());//使用 LookAndFeel 对象设置当前的默认外观
         
        }
        catch(Exception e)
        {
    
        }
       
        WebBrowser webBrowser=new WebBrowser();
        webBrowser.pack();
        webBrowser.setVisible(true);
    }
   
   
   
   
   
    class JEditorPane2 extends JEditorPane implements MouseListener {

  private static final long serialVersionUID = -2308615404205560110L;

  private JPopupMenu pop = null; // 弹出菜单

  private JMenuItem copy = null, paste = null, cut = null; // 三个功能菜单

  public JEditorPane2() {
   super();
   init();
  }

  private void init() {
   this.addMouseListener(this);
   pop = new JPopupMenu();
   pop.add(copy = new JMenuItem("COPY"));
   pop.add(paste = new JMenuItem("PASTE"));
   pop.add(cut = new JMenuItem("CUT"));
   copy.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_MASK));
   paste.setAccelerator(KeyStroke.getKeyStroke('V', InputEvent.CTRL_MASK));
   cut.setAccelerator(KeyStroke.getKeyStroke('X', InputEvent.CTRL_MASK));
   copy.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
     action(e);
    }
   });
   paste.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
     action(e);
    }
   });
   cut.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
     action(e);
    }
   });
   this.add(pop);
  }

  /**
   * 菜单动作
   * @param e
   */
  public void action(ActionEvent e) {
   String str = e.getActionCommand();
   if (str.equals(copy.getText())) { // 复制
    this.copy();
   } else if (str.equals(paste.getText())) { // 粘贴
    this.paste();
   } else if (str.equals(cut.getText())) { // 剪切
    this.cut();
   }
  }

  public JPopupMenu getPop() {
   return pop;
  }

  public void setPop(JPopupMenu pop) {
   this.pop = pop;
  }

  /**
   * 剪切板中是否有文本数据可供粘贴
   *
   * @return true为有文本数据
   */
  public boolean isClipboardString() {
   boolean b = false;
   Clipboard clipboard = this.getToolkit().getSystemClipboard();
   Transferable content = clipboard.getContents(this);
   try {
    if (content.getTransferData(DataFlavor.stringFlavor) instanceof String) {
     b = true;
    }
   } catch (Exception e) {
   }
   return b;
  }

  /**
   * 文本组件中是否具备复制的条件
   *
   * @return true为具备
   */
  public boolean isCanCopy() {
   boolean b = false;
   int start = this.getSelectionStart();
   int end = this.getSelectionEnd();
   if (start != end)
    b = true;
   return b;
  }

  public void mouseClicked(MouseEvent e) {
  }

  public void mouseEntered(MouseEvent e) {
  }

  public void mouseExited(MouseEvent e) {
  }

  public void mousePressed(MouseEvent e) {
   if (e.getButton() == MouseEvent.BUTTON3) {
    copy.setEnabled(isCanCopy());
    paste.setEnabled(isClipboardString());
    cut.setEnabled(isCanCopy());
    pop.show(this, e.getX(), e.getY());
   }
  }

  public void mouseReleased(MouseEvent e) {
  }

 }
}

 

 

.......................................................................................................................................................

 


import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileView;
import java.io.*;
import java.util.*;

class ViewSourceFrame extends JFrame implements ActionListener{
    JPanel contentPane;
    JPanel panel1 = new JPanel ();
    JPanel panel2 = new JPanel ();
    Border border1;

    JButton closebutton = new JButton ();
    JButton savebutton = new JButton ();
    JScrollPane jScrollPanel = new JScrollPane ();
    TextAreaMenu jTextArea1 = new TextAreaMenu ();

    String htmlSource;


 public ViewSourceFrame (String htmlSource) {
       
        this.htmlSource = htmlSource;
        enableEvents (AWTEvent.WINDOW_EVENT_MASK);
        setSize (new Dimension (600,500));
        setTitle ("source");
        setDefaultCloseOperation (WindowConstants.DISPOSE_ON_CLOSE);
       
        contentPane = (JPanel)getContentPane ();
        contentPane.setLayout (new BorderLayout());
       
        panel2.setLayout (new FlowLayout());
       
        savebutton.setText ("save");
        closebutton.setText ("quit");
       
  closebutton.addActionListener(this);
        savebutton.addActionListener(this);
       
        jScrollPanel.getViewport ().add (jTextArea1,null);
        border1 = BorderFactory.createEmptyBorder (4,4,4,4);
        panel1.setLayout (new BorderLayout());
        panel1.setBorder (border1);
        panel1.add (jScrollPanel,BorderLayout.CENTER);
        contentPane.add (panel1,BorderLayout.CENTER);
       
        panel2.add (savebutton);
        panel2.add (closebutton);
       
  contentPane.add (panel2,BorderLayout.SOUTH);
        this.jTextArea1.setEditable (true);
        this.jTextArea1.setText (this.htmlSource);
      
  this.jTextArea1.setCaretPosition (0);
    }
   
    /**

 */
 //.......
 class TextAreaMenu extends JTextArea implements MouseListener {

  private static final long serialVersionUID = -2308615404205560110L;

  private JPopupMenu pop = null; // 弹出菜单

  private JMenuItem copy = null, paste = null, cut = null; // 三个功能菜单

  public TextAreaMenu() {
   super();
   init();
  }

  private void init() {
   this.addMouseListener(this);
   pop = new JPopupMenu();
   pop.add(copy = new JMenuItem("COPY"));
   pop.add(paste = new JMenuItem("PASTE"));
   pop.add(cut = new JMenuItem("CUT"));
   copy.setAccelerator(KeyStroke.getKeyStroke('C', InputEvent.CTRL_MASK));
   paste.setAccelerator(KeyStroke.getKeyStroke('V', InputEvent.CTRL_MASK));
   cut.setAccelerator(KeyStroke.getKeyStroke('X', InputEvent.CTRL_MASK));
   copy.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
     action(e);
    }
   });
   paste.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
     action(e);
    }
   });
   cut.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
     action(e);
    }
   });
   this.add(pop);
  }

  /**
   * 菜单动作
   * @param e
   */
  public void action(ActionEvent e) {
   String str = e.getActionCommand();
   if (str.equals(copy.getText())) { // 复制
    this.copy();
   } else if (str.equals(paste.getText())) { // 粘贴
    this.paste();
   } else if (str.equals(cut.getText())) { // 剪切
    this.cut();
   }
  }

  public JPopupMenu getPop() {
   return pop;
  }

  public void setPop(JPopupMenu pop) {
   this.pop = pop;
  }

  /**
   * 剪切板中是否有文本数据可供粘贴
   *
   * @return true为有文本数据
   */
  public boolean isClipboardString() {
   boolean b = false;
   Clipboard clipboard = this.getToolkit().getSystemClipboard();
   Transferable content = clipboard.getContents(this);
   try {
    if (content.getTransferData(DataFlavor.stringFlavor) instanceof String) {
     b = true;
    }
   } catch (Exception e) {
   }
   return b;
  }

  /**
   * 文本组件中是否具备复制的条件
   *
   * @return true为具备
   */
  public boolean isCanCopy() {
   boolean b = false;
   int start = this.getSelectionStart();
   int end = this.getSelectionEnd();
   if (start != end)
    b = true;
   return b;
  }

  public void mouseClicked(MouseEvent e) {
  }

  public void mouseEntered(MouseEvent e) {
  }

  public void mouseExited(MouseEvent e) {
  }

  public void mousePressed(MouseEvent e) {
   if (e.getButton() == MouseEvent.BUTTON3) {
    copy.setEnabled(isCanCopy());
    paste.setEnabled(isClipboardString());
    cut.setEnabled(isCanCopy());
    pop.show(this, e.getX(), e.getY());
   }
  }

  public void mouseReleased(MouseEvent e) {
  }

 }


 
 
 //........
 public void actionPerformed(ActionEvent e) {
        String url = "";
        if (e.getSource() == closebutton){
            dispose();
        }
        else if(e.getSource() == savebutton){
            JFileChooser fc=new JFileChooser();
            int returnVal=fc.showSaveDialog(ViewSourceFrame.this);
            File saveFile=fc.getSelectedFile();
            try {
                FileWriter writeOut = new FileWriter(saveFile);
                writeOut.write(jTextArea1.getText());
                writeOut.close();
            }
            catch (IOException ex) {
                System.out.println("save faild");
            }
        }
    }
}

原创粉丝点击