package Chapter8Event; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; /* * ÓÃÄÚ²¿Àà×é֯ʼþ¼àÌý * * */ public class ButtonFram extends JFrame{ private static int DEFAULT_WIDTH=300; private static int DEFAULT_HEIGHT=200; private JPanel buttonPanel; public static void main(String[] args) { new ButtonFram(); } public ButtonFram(){ setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); /*//н¨¼àÌýÆ÷ ActionListener listenerBlack=new colorAction(Color.BLACK); ActionListener listenerYellow=new colorAction(Color.yellow); ActionListener listenerBlue=new colorAction(Color.blue); //ʵÀý»¯¼¸¸ö°´Å¥ JButton buttonBlack=new JButton("Black"); JButton buttonYellow=new JButton("Yellow"); JButton buttonBlue=new JButton("Blue"); //Ϊ°´Å¥Ìí¼Ó¼àÌý buttonBlack.addActionListener(listenerBlack); buttonYellow.addActionListener(listenerYellow); buttonBlue.addActionListener(listenerBlue); //´´½¨°´Å¥Ãæ°å£¬²¢½«°´Å¥¼ÓÈëÃæ°åÉÏ buttonPanel=new JPanel(); buttonPanel.add(buttonBlue); buttonPanel.add(buttonYellow); buttonPanel.add(buttonBlack); //½«Ãæ°åÌí¼Óµ½Fram¿ò¼ÜÉÏ this.add(buttonPanel);*/ buttonPanel=new JPanel(); setButton("Black",Color.BLACK); setButton("Yellow",Color.yellow); setButton("Blue",Color.blue); this.add(buttonPanel); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } //colorÒªÉùÃ÷Ϊfinal,²»ÐèÒªÏÔʾµÄÉùÃ÷¹¹ÔìÆ÷£¬ÄÚ²¿Àà»úÖÆ»á×Ô¶¯Éú³ÉÒ»¸ö¹¹ÔìÆ÷ public void setButton(String name,final Color bc){ JButton button=new JButton(name); //ÄäÃûÄÚ²¿Àà button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { buttonPanel.setBackground(bc); } }); buttonPanel.add(button); } /*//ÓÃÄÚ²¿Àà×éÖ¯ private class colorAction implements ActionListener{ private Color pannelColor; public colorAction(Color color){ this.pannelColor=color; } public void actionPerformed(ActionEvent e) { buttonPanel.setBackground(pannelColor); } }*/ }