62,620
社区成员
发帖
与我相关
我的任务
分享
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonTest {
public static void main(String[] args) {
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}//
}//class
@SuppressWarnings("serial")
class ButtonFrame extends JFrame {
public ButtonFrame(){
setTitle("事件监听");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
ButtonPanel panel = new ButtonPanel();
add(panel);
}//
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 300;
}//class
@SuppressWarnings("serial")
class ButtonPanel extends JPanel {
public ButtonPanel(){
JButton redButton = new JButton("RED");
JButton yellowButton = new JButton("YELLO");
JButton blueButton = new JButton("BLUE");
add(redButton);
add(yellowButton);
add(blueButton);
ColorAction yellow = new ColorAction(Color.YELLOW);
ColorAction red = new ColorAction(Color.RED);
ColorAction blue = new ColorAction(Color.BLUE);
redButton.addActionListener(red);
yellowButton.addActionListener(yellow);
blueButton.addActionListener(blue);
}//
private class ColorAction implements ActionListener {
public ColorAction( Color c){
color = c;
}
public void actionPerformed(ActionEvent e) {
setBackground(color);
}
private Color color;
}//
}//class
package com.xiaoyong;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonTest {
public static void main(String[] args) {
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
@SuppressWarnings("serial")
class ButtonFrame extends JFrame {
public ButtonFrame() {
setTitle("事件监听");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
ButtonPanel panel = new ButtonPanel();
add(panel);
}
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 300;
}
@SuppressWarnings("serial")
class ButtonPanel extends JPanel {
public ButtonPanel() {
JButton redButton = new JButton("RED");
JButton yellowButton = new JButton("YELLO");
JButton blueButton = new JButton("BLUE");
add(redButton);
add(yellowButton);
add(blueButton);
ColorAction yellow = new ColorAction(Color.YELLOW);
ColorAction red = new ColorAction(Color.RED);
ColorAction blue = new ColorAction(Color.BLUE);
redButton.addActionListener(red);
yellowButton.addActionListener(yellow);
blueButton.addActionListener(blue);
}
private class ColorAction implements ActionListener {
private Color color;
public ColorAction(Color c) {
color = c;
}
public void actionPerformed(ActionEvent e) {
setBackground(color);
}
}
}
这样就没问题了...