点击Button改变Label的值

youx 2004-03-27 07:01:26
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("ButtonTexst");
setSize(WIDTH,HEIGHT);
ButtonPanel butt= new ButtonPanel();
Container contentPane=getContentPane();
contentPane.add(butt);
}
public static final int WIDTH=300;
public static final int HEIGHT=200;
}

class ButtonPanel extends JPanel{
public ButtonPanel(){
JButton yellowButton=new JButton("Yellow");
JButton blueButton=new JButton("Blue");
JButton redButton=new JButton("Red");
JLabel label=new JLabel("label");
add(label);
add(yellowButton);
add(blueButton);
add(redButton);

ColorAction yellowAction=new ColorAction(Color.yellow);
ColorAction blueAction=new ColorAction(Color.blue);
ColorAction redAction =new ColorAction(Color.red);
yellowButton.addActionListener(yellowAction);
blueButton.addActionListener(blueAction);
redButton.addActionListener(redAction);

}
private class ColorAction extends ButtonPanel implements ActionListener{
public ColorAction(Color c){
backgroundColor=c;
}
public void actionPerformed(ActionEvent evetn){
setBackground(backgroundColor);

//为什么这里不可以引用外部类的对象label来设定它的属性??

repaint();
}
private Color backgroundColor;
}
}
...全文
583 4 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
BTXWUHEN 2004-03-27
  • 打赏
  • 举报
回复
我来迟了~
youx 2004-03-27
  • 打赏
  • 举报
回复
ok,问题解决,谢谢
youx 2004-03-27
  • 打赏
  • 举报
回复
private class ColorAction extends ButtonPanel implements ActionListener
本来是private class ColorAction implements ActionListener

不好意思,刚才我改错了,请详细解释为什么不能把label定义在构造函数里面??
非常感谢
linsy82 2004-03-27
  • 打赏
  • 举报
回复
不要把label定义在构造函数里面。内部类不能继承外部类

62,635

社区成员

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

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