abstractAction主要是可以统一定制,不需要像actionListener要一个一个去注册。
具体代码如下:
Jframe中一共3个地方用到了abstractAction:jmenuitem,jtoobar,jbutton
package testAbstractClass;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class AbstractActionDemo1 extends JFrame {
JTextArea theArea = null;
ToolBarAction pushAction = null;
public AbstractActionDemo1(){
super("AbstractAction");
theArea = new JTextArea();
theArea.setEditable(true);
this.getContentPane().add(new JScrollPane(theArea));
pushAction = new ToolBarAction("按我",null);
JMenuBar menuBar = buildJMenuBar();
menuBar.setOpaque(true);
JToolBar toolBar = buildJToolBar();
this.getContentPane().add(toolBar,BorderLayout.NORTH);
JButton jb=new JButton(pushAction);
this.getContentPane().add(jb,BorderLayout.WEST);
this.setJMenuBar(menuBar);
this.setVisible(true);
this.setBounds(new Rectangle(200,200,400,200));
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String...args){
new AbstractActionDemo1();
}
public JMenuBar buildJMenuBar(){
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
fileMenu.add(pushAction);
JMenuBar menuBar = new JMenuBar();
menuBar.add(fileMenu);
return menuBar;
}
public JToolBar buildJToolBar(){
JToolBar toolBar = new JToolBar();
toolBar.add(pushAction);
toolBar.setFloatable(true);
return toolBar;
}
class ToolBarAction extends AbstractAction{
public ToolBarAction(String name,Icon icon){
super(name,icon);
}
@Override
public void actionPerformed(ActionEvent e){
theArea.append("這是Action的好處\n");
}
}
}