Color Button
/** * * @author JJ */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ColorWindow extends JFrame { /* In here we declare the name of the button and the message JButton creates a button with a name, and JLabel writes The message on the window. Also we create a panel using JPanel, and we set the size of the window * */ private JLabel messageLabel; private JButton redButton; private JButton yellowButton; private JButton blueButton; private JPanel panel; private final int WINDOW_WIDTH = 200; private final int WINDOW_HEIGHT = 180; public ColorWindow() { /* We set the title of the window * */ setTitle("Colors"); /* We set the size of the window * */ setSize(WINDOW_WIDTH, WINDOW_HEIGHT); /* Here if the X on the top right corner is pushed, the window will close * */ setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); /* Here we will set what to display on the window * */ messageLabel = new JLabel("Click a button to select a color."); /* Here we set the name of the buttons * */ redButton = new JButton("Red"); yellowButton = new JButton("Yellow"); blueButton = new JButton("Blue"); /* Here we assign the action to the button * */ redButton.addActionListener(new RedButtonListener()); yellowButton.addActionListener(new YellowButtonListener()); blueButton.addActionListener(new BlueButtonListener()); /* Here we create the panel * */ panel = new JPanel(); /* Here we add everything to the panel * */ panel.add(messageLabel); panel.add(redButton); panel.add(yellowButton); panel.add(blueButton); add(panel); /* Finally, we set the window to be visible by making it true * */ setVisible(true); } /* Now we have to create action for the buttons Here will determines what will happen if a button is push * */ private class RedButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { panel.setBackground(Color.RED); messageLabel.setForeground(Color.BLUE); } } private class YellowButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { panel.setBackground(Color.YELLOW); messageLabel.setForeground(Color.BLACK); } } private class BlueButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { panel.setBackground(Color.BLUE); messageLabel.setForeground(Color.YELLOW); } } public static void main(String[] args) { new ColorWindow(); } }
< Java > < GUI > < Home >