日期:2014-05-20 浏览次数:20744 次
import java.awt.Color; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class BuggyButtonTest { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { BuggyButtonTestFrame frame = new BuggyButtonTestFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } class BuggyButtonTestFrame extends JFrame { public BuggyButtonTestFrame() { setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); setTitle("BuggyButtonTest"); setLocation(200, 300); // add panel BuggyButtonPanel panel = new BuggyButtonPanel(); add(panel); } private int DEFAULT_WIDTH = 200; private int DEFAULT_HEIGHT = 300; } class BuggyButtonPanel extends JPanel { public BuggyButtonPanel() { ActionListener listener = new ButtonListener(); JButton yellowButton = new JButton("yellow"); add(yellowButton); yellowButton.addActionListener(listener); JButton redButton = new JButton("red"); add(redButton); redButton.addActionListener(listener); JButton blueButton = new JButton("blue"); add(blueButton); blueButton.addActionListener(listener); } private class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { String arg = event.getActionCommand(); if (arg.equals("yellow")) { setBackground(Color.yellow); } else if (arg.equals("red")) { setBackground(Color.red); } else if (arg.equals("blue")) { setBackground(Color.blue); } } } }