Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a JMenu item do something when it's clicked

I'm making a GUI that has a Jmenu; it has the jmenu items that will be doing things when clicked. That is the problem. I've looked and looked, but I can't find out how to make it do something when clicked. Also, I am kind of a noob, so if you could make it do it in a pretty simple way, that would be great!

Here's the code:

import java.awt.Color;
import java.awt.Component;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;

public abstract class windowMaker extends JFrame implements ActionListener {
private JMenu menuFile;

public static void main(String[] args) {
    createWindow();

}

public static void createWindow() {
    JFrame frame = new JFrame();
    frame.setTitle("*Game Title* Beta 0.0.1");
    frame.setSize(600, 400);
    frame.setLocation(100, 100);
    frame.setVisible(true);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.setJMenuBar(windowMaker.menuBarCreator());
    frame.add(windowMaker.setTitle());
}

public static void launchURL(String s) {
    String s1 = System.getProperty("os.name");
    try {

        if (s1.startsWith("Windows")) {
            Runtime.getRuntime()
                    .exec((new StringBuilder())
                            .append("rundll32   url.dll,FileProtocolHandler ")
                            .append(s).toString());
        } else {
            String as[] = { "firefox", "opera", "konqueror",   "epiphany",
                    "mozilla", "netscape" };
            String s2 = null;
            for (int i = 0; i < as.length && s2 == null; i++)
                if (Runtime.getRuntime()
                        .exec(new String[] { "which", as[i]   }).waitFor() == 0)
                    s2 = as[i];

            if (s2 == null)
                throw new Exception("Could not find web browser");
            Runtime.getRuntime().exec(new String[] { s2, s });
        }
    } catch (Exception exception) {
        System.out
                .println("An error occured while trying to open the            web browser!\n");
    }
}

public static  JMenuBar menuBarCreator() {
    // create the menu parts
    JMenuBar menuBar = new JMenuBar();
    JMenu menuFile = new JMenu("File");
    JMenu menuHelp = new JMenu("Help");
    JMenuItem menuFileWebsite = new JMenuItem("Website");
    JMenuItem menuFileExit = new JMenuItem("Exit");
    JMenuItem menuHelpRules = new JMenuItem("Rules");
    JMenuItem menuHelpAbout = new JMenuItem("About");
    JMenuItem menuHelpHow = new JMenuItem("How To Play");

    // make the shortcuts for the items
    menuFile.setMnemonic(KeyEvent.VK_F);
    menuHelp.setMnemonic(KeyEvent.VK_H);

    // put the menu parts with eachother
    menuBar.add(menuFile);
    menuBar.add(menuHelp);
    menuFile.add(menuFileWebsite);
    menuFile.add(menuFileExit);
    menuHelp.add(menuHelpRules);
    menuHelp.add(menuHelpAbout);
    menuHelp.add(menuHelpHow);


    return menuBar;
}

public static Component setTitle() {
    JLabel title = new JLabel("Welcome To *the game*");
    title.setVerticalAlignment(JLabel.TOP);
    title.setHorizontalAlignment(JLabel.CENTER);
    return title;
}

}

BTW: I want the website option (let's just work with that for now) to use the launchURL method; I know that one works.

like image 277
PulsePanda Avatar asked Mar 19 '12 22:03

PulsePanda


People also ask

How do I add action listener to JMenu?

With an instance of JMenu you can't add an ActionListener, only with JMenuItem you can do it. We can add an ActionListener to JMenu , but it just doesn't have any effect. JMenu opens its child JMenu s and JMenuItem s when the mouse hovers over it.

What kind of event object is generated when a JMenuItem is selected?

Creates a menu item whose properties are taken from the specified Action .

How do I add JMenuItem to JMenu?

As the code shows, to set the menu bar for a JFrame , you use the setJMenuBar method. To add a JMenu to a JMenuBar , you use the add(JMenu) method. To add menu items and submenus to a JMenu , you use the add(JMenuItem) method.

What is menus in Java?

The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu must belong to the MenuItem or any of its subclass. The object of Menu class is a pull down menu component which is displayed on the menu bar. It inherits the MenuItem class.


3 Answers

A JMenuItem is a form of a button (AbstractButton). The normal pattern is to construct your button with an Action (see JMenuItem's constructor). The Action defines the name and action to be performed. Most people extend AbstractAction and implement actionPerformed which is invoked when the button is pressed.

A possible implementation might look like:

JMenuItem menuItem = new JMenuItem(new AbstractAction("My Menu Item") {
    public void actionPerformed(ActionEvent e) {
        // Button pressed logic goes here
    }
});

or:

JMenuItem menuItem = new JMenuItem(new MyAction());
...
public class MyAction extends AbstractAction {
    public MyAction() {
        super("My Menu Item");
    }

    public void actionPerformed(ActionEvent e) {
        // Button pressed logic goes here
    }
}

Note that everything I said above also applies to JButton. Also take a look at Java's very helpful How to Use Actions tutorial.

like image 117
Steve Kuo Avatar answered Sep 20 '22 06:09

Steve Kuo


Although it is better to use Actions, you can also add an ActionListener to your JMenuItem1 like this:

jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        jMenuItem1ActionPerformed(evt);
    }
});

and then implement the action in jMenuItem1ActionPerformed(evt):

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
    // TODO add your handling code here:
    javax.swing.JOptionPane.showMessageDialog(null, "foo");
    // more code...
}

For your code:

    ...
    JMenuItem menuFileWebsite = new JMenuItem("Website");
    JMenuItem menuFileExit = new JMenuItem("Exit");
    menuFileExit.addActionListener(new java.awt.event.ActionListener() {
        @Override
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            menuFileExitActionPerformed(evt);
        }
    });
    JMenuItem menuHelpRules = new JMenuItem("Rules");

and:

private static void menuFileExitActionPerformed(java.awt.event.ActionEvent evt) {
    System.exit(0);
}
like image 26
Costis Aivalis Avatar answered Sep 24 '22 06:09

Costis Aivalis


For adding any actions into button, just make object from class that implement ActionListener interface:

menuFileWebsite.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        launchURL("http://www.google.com");
    }
});

here we make anonymous inner object that implement Actionlistener interface, and override actionperforemed method to do its work

i make some changes in your code, to follow java standard on naming class, and create any GUI components in EDT.

// WindowMakerDemo.java

import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.*;


public final class WindowMakerDemo  {
    public static void main(String[] args) {
       EventQueue.invokeLater(new Runnable() {
           @Override
           public void run() {
                JFrame frame = new MyFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setTitle("*Game Title* Beta 0.0.1");
                frame.setSize(600, 400);
                frame.setLocation(100, 100);
                frame.setResizable(false);
                frame.setVisible(true);
           }
       });
    }
}

 final class MyFrame extends JFrame{

    public MyFrame() {
       createWindow();
    }

    private void createWindow() {
        setJMenuBar(menuBarCreator());
        add(setTitle());
    }

    private JMenuBar menuBarCreator() {
        // create the menu parts
        JMenuBar menuBar = new JMenuBar();
        JMenu menuFile = new JMenu("File");
        JMenu menuHelp = new JMenu("Help");

        JMenuItem menuFileWebsite = new JMenuItem("Website");
        JMenuItem menuFileExit = new JMenuItem("Exit");
        JMenuItem menuHelpRules = new JMenuItem("Rules");
        JMenuItem menuHelpAbout = new JMenuItem("About");
        JMenuItem menuHelpHow = new JMenuItem("How To Play");

        // website button action
        menuFileWebsite.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                launchURL("http://www.google.com");
            }
        });

        // exit action
        menuFileExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0); 
            }
        });

        // make the shortcuts for the items
        menuFile.setMnemonic(KeyEvent.VK_F);
        menuHelp.setMnemonic(KeyEvent.VK_H);

        // put the menu parts with eachother
        menuBar.add(menuFile);
        menuBar.add(menuHelp);

        menuFile.add(menuFileWebsite);
        menuFile.add(menuFileExit);

        menuHelp.add(menuHelpRules);
        menuHelp.add(menuHelpAbout);
        menuHelp.add(menuHelpHow);

        return menuBar;
    }

    private Component setTitle() {
        JLabel title = new JLabel("Welcome To *the game*");
        title.setVerticalAlignment(JLabel.TOP);
        title.setHorizontalAlignment(JLabel.CENTER);
        return title;
    }

    private void launchURL(String s) {
        String s1 = System.getProperty("os.name");
        try {

            if (s1.startsWith("Windows")) {
                Runtime.getRuntime().exec((new StringBuilder()).append("rundll32 url.dll,FileProtocolHandler ").append(s).toString());
            } else {
                String as[] = {"firefox", "opera", "konqueror", "epiphany",
                    "mozilla", "netscape"};
                String s2 = null;
                for (int i = 0; i < as.length && s2 == null; i++) {
                    if (Runtime.getRuntime().exec(new String[]{"which", as[i]}).waitFor() == 0) {
                        s2 = as[i];
                    }
                }

                if (s2 == null) {
                    throw new Exception("Could not find web browser");
                }
                Runtime.getRuntime().exec(new String[]{s2, s});
            }
        } catch (Exception exception) {
            System.out.println("An error occured while trying to open the            web browser!\n");
        }
    }
}
like image 38
Wajdy Essam Avatar answered Sep 20 '22 06:09

Wajdy Essam