java SWing事件调用的两种机制
- package test;
-
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
-
- class SimpleListener implements ActionListener {
-
- public void actionPerformed(ActionEvent e) {
- String buttonName = e.getActionCommand();
- if (buttonName.equals("按钮1"))
- System.out.println("按钮1 被点击");
-
- }
- }
-
- class ButtonAction extends AbstractAction {
-
- public void actionPerformed(ActionEvent e) {
- System.out.println("按钮2 被点击");
- }
- }
-
-
- public class ActionTest {
- private static JFrame frame;
- private static JPanel myPanel;
- private JButton button1;
- private JButton button2;
-
- public ActionTest() {
-
- myPanel = new JPanel();
-
- button1 = new JButton("按钮1");
-
- SimpleListener ourListener = new SimpleListener();
- button1.addActionListener(ourListener);
-
- button2 = new JButton();
-
- ButtonAction action = new ButtonAction();
- button2.setAction(action);
- button2.setText("按钮2");
-
- myPanel.add(button1);
- myPanel.add(button2);
- }
-
-
- public static void main(String s[]) {
- ActionTest gui = new ActionTest();
-
- frame = new JFrame("Simple1");
-
- frame.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent e) {
- System.exit(0);
- }
- });
-
- frame.getContentPane().add(myPanel);
- frame.pack();
- frame.setVisible(true);
- }
- }
原文地址:https://www.cnblogs.com/jiangzhaowei/p/7448866.html