点击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;
}
}