Sunday, January 2, 2011

JButtonMenuItem

JButtonMenuItem is a swing component to add buttons to the JMenuItem, like the edit MenuItem in Google Chrome. This is an easy to use control and can be added to the NetBeans palette. This control fires an buttonClicked event, if the button on the JButtonMenuItem is fired. The getActionCommand method of the event returns the text of the button pressed.

To handle the event you need to subscribe to JButtonMenuItemListener.

Screenshots:





Usage:
// Create a menubar for a JFrame
JMenuBar menuBar = new JMenuBar();
        
// Add the menubar to the frame
setJMenuBar(menuBar);
        
// Define and add drop down menus to the menubar
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
menuBar.add(fileMenu);
menuBar.add(editMenu);
        
// Create and add simple menu item to one of the drop down menu
JMenuItem mi = new JMenuItem("Item 1");
fileMenu.add(mi);

//get the images
ImageIcon icon = new ImageIcon(Toolkit.getDefaultToolkit().createImage(getClass().getResource("Edit_16x16.png")));

Image cutIcon = (Toolkit.getDefaultToolkit().createImage(getClass().getResource("Cut_16x16.png")));

Image copyIcon = Toolkit.getDefaultToolkit().createImage(getClass().getResource("Copy_16x16.png"));

Image pasteIcon = Toolkit.getDefaultToolkit().createImage(getClass().getResource("Paste_16x16.png"));

//create and add JButtonMenuItem to the dropdown
JButtonMenuItem mi1 = new JButtonMenuItem("Edit",icon);

//set the button style
mi1.setButtonStyle(new ButtonStyle(mi1, ButtonStyle.ROUNDED_CORNERS, ButtonStyle.ImageOrText.DISPLAY_ICON  ));

//set the buttons
mi1.setButtons(new Button[] { new Button("Cut", "Cut", cutIcon),new Button("Copy", "Copy", copyIcon),new Button("Paste", "Paste", pasteIcon)});

//subscribe to the listener
mi1.addJButtonMenuItemListener(new JButtonMenuItemListener() {
    public void buttonClicked(ActionEvent e) {
          System.out.println(e.getActionCommand());
            }
        });
fileMenu.add(mi1);

The source for this control can be downloaded from google-code.

No comments:

Post a Comment