5月29日打卡

事件处理 改变窗口背景颜色

package gvfg;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.*;
import javax.swing.*;

public class ColorTest implements ActionListener{
JFrame f;
JPanel p1,p2;
JButton b1,b2,b3;
public ColorTest() {
f=new JFrame();
p1=new JPanel();
p2=new JPanel();
b1 = new JButton("黄色");
b1.addActionListener(this);
b2 = new JButton("蓝色");
b2.addActionListener(this);
b3 = new JButton("绿色");
b3.addActionListener(this);
p1.add(b1);
p1.add(b2);
p1.add(b3);
f.add(p1,BorderLayout.NORTH);
f.add(p2,BorderLayout.CENTER);
f.setSize(400,300);
f.setVisible(true);
}
public static void main(String[] args) {
new ColorTest();
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==b1)// TODO Auto-generated method stub
p2.setBackground(Color.yellow);
if(e.getSource()==b2)// TODO Auto-generated method stub
p2.setBackground(Color.blue);
if(e.getSource()==b3)// TODO Auto-generated method stub
p2.setBackground(Color.green);
}

}

原文地址:https://www.cnblogs.com/za-ys/p/10945050.html