package button; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class buttonFrame extends JFrame{ private JPanel buttonPanel; private static final int D_width=300; private static final int D_height=200; public static void main(String args[]){ JFrame frame = new buttonFrame(); frame.setTitle("buttonFrame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } public buttonFrame(){ setSize(D_width,D_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); ColorAction yellowAction = new ColorAction(Color.YELLOW); ColorAction blueAction = new ColorAction(Color.BLUE); ColorAction 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 event){ buttonPanel.setBackground(backgroundColor); } } }
时间: 2024-09-29 03:29:11