package swingExamples; import javax.swing.*; import java.awt.*; import java.awt.event.*; // JPanel demo from "Absolute Java" // with some modifications public class PanelDemo extends JFrame implements ActionListener { private JPanel greenPanel; private JPanel whitePanel; private JPanel grayPanel; private JButton greenButton, whiteButton, grayButton; public static void main(String[] args) { PanelDemo gui = new PanelDemo( ); gui.setVisible(true); } public PanelDemo( ) { super("Panel Demonstration"); setSize(300, 300); setLocation(200, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout( )); // mainPanel contains the panels that show the colors JPanel mainPanel = new JPanel( ); mainPanel.setLayout(new GridLayout(1, 3)); greenPanel = new JPanel( ); greenPanel.setBackground(Color.LIGHT_GRAY); mainPanel.add(greenPanel); whitePanel = new JPanel( ); whitePanel.setBackground(Color.LIGHT_GRAY); mainPanel.add(whitePanel); grayPanel = new JPanel( ); grayPanel.setBackground(Color.LIGHT_GRAY); mainPanel.add(grayPanel); add(mainPanel, BorderLayout.CENTER); // buttonPanel holds the buttons at the bottom of the screen JPanel buttonPanel = new JPanel( ); buttonPanel.setBackground(Color.LIGHT_GRAY); buttonPanel.setLayout(new FlowLayout( )); greenButton = new JButton("Green"); greenButton.setBackground(Color.GREEN); greenButton.addActionListener(this); buttonPanel.add(greenButton); whiteButton = new JButton("White"); whiteButton.setBackground(Color.WHITE); whiteButton.addActionListener(this); buttonPanel.add(whiteButton); grayButton = new JButton("Gray"); grayButton.setBackground(Color.GRAY); grayButton.addActionListener(this); buttonPanel.add(grayButton); add(buttonPanel, BorderLayout.SOUTH); } // one ActionListener for all the buttons public void actionPerformed(ActionEvent e) { // determine which button was the event source if (e.getSource() == greenButton) greenPanel.setBackground(Color.GREEN); else if (e.getSource() == whiteButton) whitePanel.setBackground(Color.WHITE); else if (e.getSource() == grayButton) grayPanel.setBackground(Color.GRAY); else System.out.println("Unexpected error."); } }