我的程序是在面板中添加2个按钮,当单击相应的按钮时,改变背景颜色,我想用ColorAction这个类实现监听但是总是提示,没有为类型 ColorAction 定义方法 setBackground(Color),不过我用内部类实现了,请高手指教!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FrameTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
boolean t=true;
Frame frame=new Frame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(t);
}
}
class Frame extends JFrame
{
public Frame()
{
setTitle("FrameTest");
setSize(W,H);
FramePanel panel=new FramePanel();
add(panel);
}
private static final long serialVersionUID=20070609;
public static final int W=300;
public static final int H=200;
}
class FramePanel extends JPanel
{
public FramePanel()
{
JButton yellow=new JButton("yellow");
JButton green=new JButton("green");
add(yellow);
add(green);
ColorAction yellowAction=new ColorAction(Color.YELLOW);
ColorAction greenAction=new ColorAction(Color.GREEN);
yellow.addActionListener(yellowAction);
green.addActionListener(greenAction);
}
private static final long serialVersionUID=20070609;
}
class ColorAction implements ActionListener
{
public ColorAction(Color c)
{
backgroundColor=c;
}
public void actionPerformed(ActionEvent event)
{
setBackground(backgroundColor); //没有为类型 ColorAction 定义方法 setBackground(Color)
}
private Color backgroundColor;
}