Wednesday, June 13, 2012

Example of using Swing JMenu

Example of using Swing JMenu


Modify JFrameWin.java from last exercise - "Run a JFrame application using SwingUtilities.invokeLater".

package javatestswing;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JFrameWin extends JFrame{
    
    public JFrameWin(){
        
        this.setTitle("java-buddy.blogspot.com");
        this.setSize(500, 400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                
        JButton buttonExit = new JButton(" Exit ");
        buttonExit.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent ae) {
                System.exit(0);
            }
        });

        this.add(buttonExit);
        
        JMenuBar menuBar = new JMenuBar();
        
        JMenu menuA = new JMenu("Menu A");
        JMenuItem menuItemA1 = new JMenuItem("Menu Item A 1");
        JMenuItem menuItemA2 = new JMenuItem("Menu Item A 2");
        JMenuItem menuItemA3 = new JMenuItem("Menu Item A 3");
        menuA.add(menuItemA1);
        menuA.add(menuItemA2);
        menuA.addSeparator();
        menuA.add(menuItemA3);
        
        JMenu menuB = new JMenu("Quit...");
        JMenuItem menuItemB1 = new JMenuItem("Exit");
        menuItemB1.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent ae) {
                System.exit(0);
            }
        });
        menuB.add(menuItemB1);

        
        menuBar.add(menuA);
        menuBar.add(menuB);
        this.setJMenuBar(menuBar);
        
    }
    
}


No comments:

Post a Comment