Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import javax.swing.JFrame;
- import javax.swing.JPanel;
- import javax.swing.JButton;
- import javax.swing.JMenu;
- import javax.swing.JMenuItem;
- import javax.swing.JMenuBar;
- import java.awt.GridLayout;
- import java.awt.Color;
- import java.awt.event.ActionListener;
- import java.awt.event.ActionEvent;
- public class MenuDemo extends JFrame implements ActionListener {
- public static final int WIDTH = 300; // extending JFrame because MenuDemo needs a JFrame
- // gui needs a JFrame..the outline.
- // implementing ActionListener whenever we need to perform actions
- // implements are for interfaces and interfaces have abstract methods no complete methods
- public static final int HEIGHT = 200;
- private static final JButton JButton = null;
- private JPanel greenPanel; // creating JPanels
- private JPanel whitePanel;
- private JPanel grayPanel;
- public static void main(String[] args)
- {
- MenuDemo gui = new MenuDemo();
- gui.setVisible(true);
- }
- public MenuDemo() // MenuDemo constructor
- {
- super("Menu Demonstration"); //
- setSize(WIDTH, HEIGHT);
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setLayout(new GridLayout(1, 3));
- greenPanel = new JPanel();
- greenPanel.setBackground(Color.LIGHT_GRAY);
- add(greenPanel);
- whitePanel = new JPanel();
- whitePanel.setBackground(Color.LIGHT_GRAY);
- add(whitePanel);
- grayPanel = new JPanel();
- grayPanel.setBackground(Color.LIGHT_GRAY);
- add(grayPanel);
- JMenu colorMenu = new JMenu("Add Colors");
- JMenuItem greenChoice = new JMenuItem("Green");
- greenChoice.addActionListener(this);
- colorMenu.add(greenChoice);
- JMenuItem whiteChoice = new JMenuItem("White");
- whiteChoice.addActionListener(this);
- colorMenu.add(whiteChoise);
- JMenuItem grayChoice = new JMenuItem("Gray");
- grayChoice.addActionListener(this);
- colorMenu.add(grayChoice);
- JMenuBar bar = new JMenuBar();
- bar.add(colorMenu);
- setJMenuBar(bar);
- }
- public void actionPerformed(ActionEvent e)
- {
- String buttonSring = e.getActionCommand();
- if (buttonString.equals("Green"))
- greenPanel.setBckground(Color.GREEN);
- else if (buttonString.equals("White"))
- whitePanel.setBackground(Color.WHITE);
- else if (buttonString.equals("Gray"))
- grayPanel.setBackground(Color.GRAY);
- else
- System.out.println("Unexpected error.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement