有很多种方式定义监听类,哪种方式比较好呢?
使用内部类或者匿名内部类定义监听类已经成了事件处理程序设计的标准。
因为他通常都能提供清晰、干净和简洁的代码。
package chapter16; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; @SuppressWarnings("serial") public class DetectSourceDemo extends JFrame{ private JButton sNew = new JButton ("Process New"); private JButton sOpen = new JButton ("Process Open"); private JButton sSave = new JButton ("Process Save"); private JButton sPrint = new JButton ("Process Print"); public DetectSourceDemo(){ setLayout(new FlowLayout()); add(sNew); add(sOpen); add(sSave); add(sPrint); sNew.addActionListener(new ButtonListener()); sOpen.addActionListener(new ButtonListener()); sSave.addActionListener(new ButtonListener()); sPrint.addActionListener(new ButtonListener()); } public static void main(String[] args) { JFrame frame = new DetectSourceDemo(); frame.setTitle("Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.pack(); frame.setVisible(true); } class ButtonListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==sNew){ System.out.println("new"); } else if(e.getSource()==sOpen){ System.out.println("open"); } else if(e.getSource()==sSave){ System.out.println("save"); } else { System.out.println("print"); } } } }
/** * 这种方法不是很好,因为将太多的责任放在了一个类中,最好能设计一个监听类 ,只负责处理事件,这种设计会让代码易于阅读和维护 */ package chapter16; import javax.swing.*; import java.awt.event.*; @SuppressWarnings("serial") public class FrameAsListenerDemo extends JFrame implements ActionListener { // Create four buttons private JButton jbtNew = new JButton("New"); private JButton jbtOpen = new JButton("Open"); private JButton jbtSave = new JButton("Save"); private JButton jbtPrint = new JButton("Print"); public FrameAsListenerDemo() { // Create a panel to hold buttons JPanel panel = new JPanel(); panel.add(jbtNew); panel.add(jbtOpen); panel.add(jbtSave); panel.add(jbtPrint); add(panel); // Register listener with buttons jbtNew.addActionListener(this); jbtOpen.addActionListener(this); jbtSave.addActionListener(this); jbtPrint.addActionListener(this); } /** Implement actionPerformed */ public void actionPerformed(ActionEvent e) { if (e.getSource() == jbtNew) System.out.println("Process New"); else if (e.getSource() == jbtOpen) System.out.println("Process Open"); else if (e.getSource() == jbtSave) System.out.println("Process Save"); else if (e.getSource() == jbtPrint) System.out.println("Process Print"); } /** Main method */ public static void main(String[] args) { JFrame frame = new FrameAsListenerDemo(); frame.setTitle("FrameAsListenerDemo"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }
时间: 2024-10-03 07:30:04