返回信息流在看core java事件处理的部分,照着书上程序改了改,不知道为啥老出错,请哪位大牛有空帮忙看看,谢谢
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args)
{
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(500,500);
}
}
class ButtonFrame extends JFrame
{
public ButtonFrame()
{
setTitle("ButtonTest");
makebutton("yellow", Color.YELLOW);
makebutton("red", Color.RED);
add(buttonPanel);
}
public void makebutton(String name, Color background)
{
JButton button = new JButton(name);
buttonPanel.add(button);
ColorAction action = new ColorAction(background);
button.addActionListener(action);
}
private class ColorAction implements ActionListener
{
public ColorAction(Color c) {
// TODO Auto-generated constructor stub
backgroundColor = c;
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
buttonPanel.setBackground(backgroundColor);
}
private Color backgroundColor;
}
private JPanel buttonPanel;
}
这是一条镜像帖。来源:北邮人论坛 / java / #24183同步于 2013/1/8
该镜像源已超过 30 天没有更新,可能在源站已被删除。
Java机器人发帖
关于事件处理的一个小程序,请教
RG
2013/1/8镜像同步6 回复
订阅后,新回复会通过你的通知中心匿名送达。
6 条回复
【 在 RG 的大作中提到: 】
: 在看core java事件处理的部分,照着书上程序改了改,不知道为啥老出错,请哪位大牛有空帮忙看看,谢谢
: import java.awt.Color;
: import java.awt.EventQueue;
: ...................
把这一行:private JPanel buttonPanel;
换成: JPanel buttonPanel = new JPanel();
为什么这样,其实我也解释不清楚,呵呵,之前你的报空指针的错误,所以我觉得需要对buttonPanel这个对象进行实例化吧。
【 在 idyllic 的大作中提到: 】
: 手头没有电脑,不知以下对错
: 构造器需要调用super构造器吧,还有楼上说的也得加上
其实不加super也行,它会自动调用超类的无参构造方法~ 测试过啦~
【 在 idyllic 的大作中提到: 】
: 手头没有电脑,不知以下对错
: 构造器需要调用super构造器吧,还有楼上说的也得加上
当然,加上也不会报错,呵呵
【 在 feibingbing 的大作中提到: 】
: 把这一行:private JPanel buttonPanel;
: 换成: JPanel buttonPanel = new JPanel();
: 为什么这样,其实我也解释不清楚,呵呵,之前你的报空指针的错误,所以我觉得需要对buttonPanel这个对象进行实例化吧。
哦,懂了,谢谢