62,616
社区成员
发帖
与我相关
我的任务
分享
private class ColorAction implements ActionListener
{
private Color backgroundColor;
public ColorAction(Color n)
{
backgroundColor = n;
}
public void actionPerformed(ActionEvent e)
{
setBackground(backgroundColor);
}
}
package com.csdn;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ButtonTest {
public static void main(String[] args) {
Myframe frame = new Myframe();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class Myframe extends JFrame {
public Myframe() {
setTitle("MY FRAME");
setSize(300, 400);
Mypanel panel = new Mypanel();
add(panel);
}
}
class Mypanel extends JPanel {
// private Color backgroundColor;
public Mypanel() {
JButton button1 = new JButton("yellow");
JButton button2 = new JButton("blue");
JButton button3 = new JButton("red");
add(button1);
add(button2);
add(button3);
ColorAction ColorYellow = new ColorAction(Color.YELLOW);
ColorAction ColorBlue = new ColorAction(Color.BLUE);
ColorAction ColorRed = new ColorAction(Color.RED);
button1.addActionListener(ColorYellow);
button2.addActionListener(ColorBlue);
button3.addActionListener(ColorRed);
}
private class ColorAction implements ActionListener {
Color backgroundColor;
public ColorAction(Color n) {
this.backgroundColor = n;
}
public void actionPerformed(ActionEvent e)
{
setBackground(backgroundColor);
}
}
}