2012-03-19 5 views
8

私はJmenuを持つGUIを作っています。クリックしたときに動作するjmenu項目があります。それが問題だ。私は見て見ましたが、クリックすると何かをする方法を見つけることができません。また、私は一種のノブなので、あなたがそれをかなり簡単な方法で行うことができれば、それは素晴らしいだろう!クリックしたときにJMenuアイテムを何かするには

ここでコードは次のとおりです。ところで

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

} 

:私はlaunchURLメソッドを使用するには、Webサイトのオプションを(ちょうど今のものと協力しましょう)したいです。私は一つが働くことを知っている。

答えて

10

JMenuItemは、ボタン(AbstractButton)の形式です。通常のパターンはActionJMenuItemのコンストラクタを参照)でボタンを作成することです。 Actionは、実行される名前とアクションを定義します。ほとんどの人はAbstractActionを拡張し、ボタンを押したときに呼び出されるactionPerformedを実装します。私は上記の言ったすべてがまたJButtonに適用されることを

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

注:

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

か:

可能な実装は、次のようになります。また、Javaの非常に役立つHow to Use Actionsチュートリアルを見てください。

+0

私はそれをどうしますか? – PulsePanda

+0

['FileMenu'](http://stackoverflow.com/a/4039359/230513)は、関連する例です。 – trashgod

+0

hmmmm、それはどのように役立つかもしれませんが、私はそれを実装する方法を理解していません...私は私のコードの一部を使用することができますか?心に留めて、私はnooby – PulsePanda

2

あなたはちょうどこのようなあなたのJMenuItem1にActionListenerを追加する必要があります。

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

、その後jMenuItem1ActionPerformed(EVT)内のアクションを実装:あなたのコードのために

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) { 
    // TODO add your handling code here: 
    javax.swing.JOptionPane.showMessageDialog(null, "foo"); 
    // more 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"); 

と:

ボタンに任意のアクションを追加するための
private static void menuFileExitActionPerformed(java.awt.event.ActionEvent evt) { 
    System.exit(0); 
} 
+0

actionListener()ではなくActionsを使用するほうがはるかに優れています。アクションには再利用できるメリットがあります。アクションを無効にすると、そのアクションを使用するすべてのGUIエレメントも無効になります。それはまた、はるかにクリーンなデザインIMHOです。 – Michael

1

、ちょうどActionListenerインタフェースを実装するクラスからオブジェクトを作る:

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

ここで我々はActionListenerインタフェースを実装する匿名の内部オブジェクトを作成し、その作業

を行うためのactionperforemedメソッドをオーバーライド

あなたのコードをいくつか変更し、名前付けクラスのJava標準に従い、EDTにGUIコンポーネントを作成します。

// 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"); 
     } 
    } 
} 
関連する問題