[java]代码库
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class T2 extends JFrame{
private JButton hongse = new JButton("红色");
private JButton huangse = new JButton("黄色");
private JButton lvse= new JButton("绿色");
private JButton chengse = new JButton("橙色");
private JButton lanse = new JButton("蓝色");
private JLabel text = new JLabel("这里是一段话");
private JPanel jp1 = new JPanel();
private JPanel jp2 = new JPanel();
public T2(){
//初始化画框
this.setTitle("按钮事件");
this.setSize(800, 600);
this.setDefaultCloseOperation(2);
this.setVisible(true);
//把控件添加到画板
this.jp1.add(hongse);
this.jp1.add(huangse);
this.jp1.add(lvse);
this.jp1.add(chengse);
this.jp1.add(lanse);
this.jp2.add(text);
this.add(jp1,BorderLayout.NORTH);
this.add(jp2);
//给jp1加个边框
this.jp1.setBorder(BorderFactory.createTitledBorder("改变颜色"));
//给jp2加个颜色
this.jp2.setBackground(Color.lightGray);
//给按钮添加事件
this.hongse.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
text.setForeground(Color.red);
}
});
this.huangse.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
text.setForeground(Color.yellow);
}
});
this.lvse.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
text.setForeground(Color.green);
}
});
this.chengse.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
text.setForeground(Color.orange);
}
});
this.lanse.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
text.setForeground(Color.blue);
}
});
}
public static void main(String[] args) {
new T2();
}
}