事件处理.三个按钮.背景改变
package demo; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class MyFrame implements ActionListener { JPanel p1,p2; JFrame f; JButton b1,b2,b3; public MyFrame(){ 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); f.add(p1,BorderLayout.NORTH); p1.add(b1); p1.add(b2); p1.add(b3); f.add(p2,BorderLayout.CENTER); f.setSize(300,200); f.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { // TODO 自动生成的方法存根 if(e.getSource() == b1) p2.setBackground(Color.red); if(e.getActionCommand().equals("粉")) p2.setBackground(Color.pink); if(e.getSource() == b3) p2.setBackground(Color.green); } public static void main(String[]args){ new MyFrame(); } }
刚开始并不会三个颜色的切换,还是靠老师教了。