简介
java 事件处理机制
code
/*
* @Author: your name
* @Date: 2020-10-28 22:38:26
* @LastEditTime: 2020-10-29 10:01:15
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: /java/ImageTest.java
*/
import java.awt.*;
import javax.swing.*;
public class ImageTest {
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new ButtonFrame();
frame.setTitle("ImageTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
;
}
}
/*
* @Author: your name
* @Date: 2020-10-29 09:41:06
* @LastEditTime: 2020-10-29 10:01:27
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: /java/ButtonFrame.java
*/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonFrame extends JFrame {
private JPanel buttonPanel;
private static final int DEFAULT_WIDTH = 300;
private static final int DEFAULT_HEIGHT = 200;
public ButtonFrame() {
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// create button
JButton yellowButton = new JButton("Yellow");
JButton blueButton = new JButton("Blue");
JButton redButton = new JButton("Red");
buttonPanel = new JPanel();
// add buttons to panel
buttonPanel.add(yellowButton);
buttonPanel.add(blueButton);
buttonPanel.add(redButton);
add(buttonPanel);
// create button actions
ColorAction yellowAction = new ColorAction(Color.YELLOW);
ColorAction blueAction = new ColorAction(Color.BLUE);
ColorAction redAction = new ColorAction(Color.RED);
// associate actions with buttons
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);
}
private class ColorAction implements ActionListener {
private Color backgroundColor;
public ColorAction(Color c) {
backgroundColor = c;
}
public void actionPerformed(ActionEvent event) {
buttonPanel.setBackground(backgroundColor);
}
}
}