事件监听实现的套路
版本1
package com.uos.server;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
public class InterfaceInit {
private static JFrame jFrame;
private static JPanel jPanel;
class SimpleListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String buttonName = e.getActionCommand();
if (buttonName.equals("干起来")) {
JOptionPane.showMessageDialog(jFrame, "弄疼我了");
System.out.println("干嘛呀");
} else if (buttonName.equals("动起来")) {
JOptionPane.showMessageDialog(jFrame, "爱死我了");
System.out.println("恩恩爱呀");
}
}
}
public void init() {
jFrame = new JFrame("监听事件练习");
jPanel = new JPanel();
JButton jButton1 = new JButton("干起来");
JButton jButton2 = new JButton("动起来");
SimpleListener simpleListener = new SimpleListener();
jButton1.addActionListener(simpleListener);
jButton2.addActionListener(simpleListener);
jPanel.add(jButton1);
jPanel.add(jButton2);
jFrame.add(jPanel);
jFrame.pack();
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new InterfaceInit().init();
}
}
版本2
package com.uos.server;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
public class InterfaceInit {
private static JFrame jFrame;
private static JPanel jPanel;
JButton jButton1;
JButton jButton2;
public void init() {
jFrame = new JFrame("监听事件练习");
jPanel = new JPanel();
jButton1 = new JButton("干起来");
jButton2 = new JButton("动起来");
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(jFrame,"中层干部动起来");
}
});
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(jFrame,"底层动部动起来");
}
});
jPanel.add(jButton1);
jPanel.add(jButton2);
jFrame.add(jPanel);
jFrame.pack();
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new InterfaceInit().init();
}
}
参考文献
posted on 2020-06-17 14:52 Indian_Mysore 阅读(55) 评论(0) 收藏 举报
浙公网安备 33010602011771号