Java 100-003:利用按鈕實現更換背景的效果
阿新 • • 發佈:2018-12-30
package java01; import java.awt.Color; import java.awt.event.*; import javax.swing.*; /** * 我的java每天100行程式碼003 * 利用按鈕實現更換背景的效果 * @author Administrator * */ public class java003{ public static void main(String[] args) { ButtonFrame frame = new ButtonFrame(); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); } } class ButtonFrame extends JFrame{ private JPanel buttonPanel; private static final int DEFAULT_WIDTH = 300; private static final int DEFAULT_HEIGHT = 200; public ButtonFrame() { setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT); JButton yellowButton = new JButton("yellow"); JButton blueButton = new JButton("blue"); JButton redButton = new JButton("red"); buttonPanel = new JPanel(); buttonPanel.add(yellowButton); buttonPanel.add(blueButton); buttonPanel.add(redButton); add(buttonPanel); ActionListener yellowAction = new ColorAction(Color.YELLOW); ActionListener blueAction = new ColorAction(Color.BLUE); ActionListener redAction = new ColorAction(Color.RED); yellowButton.addActionListener(yellowAction); blueButton.addActionListener(blueAction); redButton.addActionListener(redAction); } //靜態內部類 private class ColorAction implements ActionListener{ private Color backgroundColor; public ColorAction(Color c){ backgroundColor = c; } public void actionPerformed(ActionEvent e) { buttonPanel.setBackground(backgroundColor); } } }