2012-04-17 101 views
-1

我希望將相同的JMenuItem添加到多個JMenus,但它只顯示最後一個JMenu。這是我寫的代碼。我想爲所有JMenu狀態顯示三個JMenu項目。通過這個代碼,前兩個狀態沒有JMenuItems,所有三個都只有最後一個。將JMenuItem添加到多個菜單

import javax.swing.*; 
import java.awt.event.*; 
public class Menu extends JFrame{ 
    public Menu() 
    { 
    super("Funky Menu"); 
JMenu [] states = new JMenu [3]; 
JMenuItem [] items = new JMenuItem [3]; 
//Initializing the items 
items[0] = new JMenuItem("Industries"); 
items[0].setMnemonic('I'); 
items[1] = new JMenuItem("Hill Stations"); 
items[1].setMnemonic('H'); 
items[2] = new JMenuItem("Top Institutions"); 
items[2].setMnemonic('T'); 
//Initializing the states 
//I've set the adjacent keys as the Mnemonics for easy user interaction 
//though it is less intuitive, it can vary on the user preference. 
states[0] = new JMenu("Tamil Nadu"); states[0].setMnemonic('Q'); 
states[1] = new JMenu("West Bengal"); states[1].setMnemonic('W'); 
states[2] = new JMenu("Haryana"); states[2].setMnemonic('E'); 
//Adding all the items to each of the states 
for(int i=0; i<3; ++i) 
{ 
    for(int j=0; j<3; ++j) 
    { 
    states[i].add(items[j]); 
    } 
} 
//adding action listener to menu items 
for(int j=0; j<3; ++j) 
{ 
    items[j].addActionListener(new ActionListener(){ 
    public void actionPerformed(ActionEvent evt) 
    { 
    //The next few lines could be clubbed together in one but for 
    //clarity sake I write them seperately 
    JMenuItem currentItem = (JMenuItem) evt.getSource(); 
    String textToDisplay = currentItem.getText(); 
    System.out.println(textToDisplay + " : located in ..."); 
    //one liner : System.out.println(((JMenuItem) evt.getSource()).getText() + " : located in ..."); 
    } 
    }); 
} 
//finally to fix up the MenuBar 
JMenuBar bar = new JMenuBar(); 
setJMenuBar(bar); 
for(int i=0; i<3; ++i) 
{ 
    bar.add(states[i]); 
} 
getContentPane(); 
//TODO Create a JLabel add it to the contents 
//Instead of writing to the console, update the frames text 
setSize(500, 500); 
setVisible(true); 
} 

    public static void main(String[] args) 
    { 
    Menu app = new Menu(); 
    app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    } 
} 
+0

我應該如何替換JMenuItem? – nikhil 2012-04-17 16:48:07

回答

3

我沒有檢查你的代碼,但一個組件只能有一個父代。您需要創建單獨的菜單項(可能使用相同的Action對象)。

+1

@nikhil和使用ClassName菜單是AWT菜單的保留字,將其更改爲MyMenu – mKorbel 2012-04-17 17:16:39

2

@Puce是正確的。相反,請使用Action來封裝共享功能,並使用Action的常見實例構建單個菜單項。 FileMenu就是一個簡單的例子。