2012-03-19 9 views
8

Sto facendo una GUI che ha un Jmenu; ha gli elementi jmenu che faranno cose quando cliccato. Quello è il problema. Ho guardato e guardato, ma non riesco a scoprire come farlo fare qualcosa quando si fa clic. Inoltre, sono una specie di noob, quindi se potessi farlo farlo in un modo piuttosto semplice, sarebbe fantastico!Come fare un oggetto JMenu fare qualcosa quando viene cliccato

Ecco il codice:

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: Voglio l'opzione sito web (facciamo solo lavoro con quello per ora) di utilizzare il metodo launchURL; So che uno funziona.

risposta

10

A JMenuItem è una forma di un pulsante (AbstractButton). Lo schema normale consiste nel costruire il tuo pulsante con un Action (vedi costruttore di JMenuItem). Il Action definisce il nome e l'azione da eseguire. La maggior parte delle persone si estende allo AbstractAction e implementa actionPerformed che viene richiamato quando si preme il pulsante.

Una possibile applicazione potrebbe essere simile:

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

o:

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 
    } 
} 

Nota che tutto ciò che ho detto sopra vale anche per JButton. Dai anche un'occhiata al molto utile tutorial Java How to Use Actions.

+0

ok, quindi come faccio? – PulsePanda

+0

['FileMenu'] (http://stackoverflow.com/a/4039359/230513) è un esempio correlato. – trashgod

+0

hmmmm, vedo come potrebbe essere utile, ma non capisco come implementarlo ... potremmo usare parte del mio codice? tieni a mente, im nooby – PulsePanda

2

Hai solo bisogno di aggiungere un ActionListener ai tuoi JMenuItem1 in questo modo:

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

e quindi implementare l'azione 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... 
} 

Per il tuo codice:

... 
    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"); 

e:

private static void menuFileExitActionPerformed(java.awt.event.ActionEvent evt) { 
    System.exit(0); 
} 
+0

È molto meglio usare Actions piuttosto che actionListener(). Le azioni hanno il vantaggio che possono essere riutilizzate e se si disattiva un'azione, anche tutti gli elementi della GUI che utilizzano quell'azione sono disabilitati. È anche molto più pulito design IMHO. – Michael

1

Per l'aggiunta di tutte le azioni in pulsante, basta fare oggetto dalla classe che implementa l'interfaccia ActionListener:

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

qui facciamo anonima oggetto interno che implementa l'interfaccia ActionListener, e sovrascrivere actionperforemed metodo per fare il suo lavoro

Apporto alcune modifiche al codice, per seguire lo standard java sulla classe di denominazione e creare qualsiasi componente della GUI 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"); 
     } 
    } 
}