2012-07-27 65 views
0

我想添加一個動作偵聽器添加到JMenu的字符串......不知道如何做到這一點,JavaDoc並沒有讓它更容易找出如何。這裏是我的代碼:添加動作偵聽器到字符串

import javax.swing.*; 
import java.awt.event.*; 

public class GUI extends JFrame implements ActionListener{ 

private static final long serialVersionUID = 234614L; 

private static final JMenuBar menbar = new JMenuBar(); 

private static final JMenu blocks = new JMenu("name"); 
private static final JMenu items = new JMenu("name2"); 

private static final JMenu edit = new JMenu("Edit"); 

    public GUI(){ 

     this.setSize(300, 200); 
     this.setTitle(""); 

     this.setJMenuBar(menbar); 

     menbar.add(blocks); 
     menbar.add(items); 
     menbar.add(edit); 

     blocks.add("Stone"); 

     blocks.addActionListener(this); 

    } 

    public void actionPerformed(ActionEvent e) { 



    } 

} 
+2

有什麼問題嗎? – 2012-07-27 00:26:12

+0

我想一個動作監聽器添加到字符串 – SuperCheezGi 2012-08-09 02:09:37

+0

啊,又是十二歲 – SuperCheezGi 2017-02-20 17:01:30

回答

3

.add(String s)返回JMenuItem,你需要採取的參考,你就可以添加一個動作監聽。

JMenuItem stoneMenuItem = blocks.add("Stone"); 
stoneMenuItem.addActionListener(new ActionListener() { 
    // My stuff! 
}); 
相關問題