窗口三个按钮程序的错误,请帮忙解决!(书中原例子)

ladofwind 2003-08-11 04:09:47
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ButtonTest{
public static void main(String []args)
{
ButtonFrame frame=new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
}
}

class ButtonFrame extends JFrame
{
public ButtonFrame()
{
setTitle("ButtonTest");
setSize(300,300);

ButtonPanel panel=new ButtonPanel();
Container contentPane=getContentPane();
contentPane.add(panel);
}
}

class ButtonPanel extends JPanel
{
public ButtonPanel()
{
JButton b1=new JButton("Yellow");
JButton b2=new JButton("Blue");
JButton b3=new JButton("Red");

add(b1);
add(b2);
add(b3);

ColorAction yellowAction=new ColorAction(Color.yellow);
ColorAction blueAction=new ColorAction(Color.blue);
ColorAction redAction=new ColorAction(Color.red);

b1.addActionListener(yellowAction);
b2.addActionListener(blueAction);
b3.addActionListener(redAction);
}

}

class ColorAction implements ActionListener
{
private Color backgroundColor;
public ColorAction(Color c)
{
backgroundColor=c;
}
public void actionPerformed(ActionEvent event)
{

setBackground(Color.yellow);//错误出现处~~
}

}
...全文
12 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
fpwang 2003-08-11
  • 打赏
  • 举报
回复
public void actionPerformed(ActionEvent event)
{

bp.setBackground(c);//错误出现处~~
}
试试可以么
如果不行,要么就实现三个监听器,不同监听器改变不同颜色
要么在监听器中,判断发生事件的控件,然后根据判断改变不同颜色,好像用getSource()得到产生事件的控件
ladofwind 2003-08-11
  • 打赏
  • 举报
回复
这样一来颜色好象只能设一次!再点其他按钮就不行?
fpwang 2003-08-11
  • 打赏
  • 举报
回复
class ButtonPanel extends JPanel{
……
public ButtonPanel(){
……
ColorAction yellowAction=new ColorAction(Color.yellow,this);
ColorAction blueAction=new ColorAction(Color.blue,this);
ColorAction redAction=new ColorAction(Color.red,this);
……
}
……
}
fpwang 2003-08-11
  • 打赏
  • 举报
回复
class ColorAction implements ActionListener
{
private Color backgroundColor;
ButtonPanel bp;
public ColorAction(Color c, ButtonPanel bp)
{
backgroundColor=c;
this.bp=bp;//this是当前对象的指针
}
public void actionPerformed(ActionEvent event)
{

bp.setBackground(Color.yellow);//错误出现处~~
}

}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧