对应按钮和颜色的切换

编写一个程序,创建一个AWT面板,该面板包含有三个不同颜色名称的桑按钮,单击每个按钮时应使窗口的背景颜色显示为相应的颜色。

public class Colortest extends Frame implements ActionListener{

    Button b1,b2,b3;
    Panel p=new Panel();

public static void main(String args[]) {
    Colortest c=new Colortest();
    c.init();
    c.setSize(200,200);
    c.setVisible(true);
}

public void init() {
    
    b1=new Button("红色");
    b2=new Button("蓝色");
    b3=new Button("黄色");
    p.add(b1);
    p.add(b2);
    p.add(b3);
    this.add(p);
    
    b1.addActionListener(this);
    b2.addActionListener(this);
    b3.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if(e.getSource()==b1) {
        p.setBackground(Color.red);
    }
    else if(e.getSource()==b2) {
        p.setBackground(Color.BLUE);
    }
    else p.setBackground(Color.yellow);
}
}

运行结果:

猜你喜欢

转载自blog.csdn.net/xxx_1_1/article/details/81347294