当我运行此代码时,只显示Splitpane但不显示JMenu

时间:2017-11-05 15:29:11

标签: java jmenu splitpane

当我运行此代码时,界面将被拆分,但我用来使JMenu显示的代码没有错误。我已经尝试了一切,但似乎没有任何工作。

public class Task1panel extends JFrame {
    public static JMenuBar setupMenu() {
        JMenuBar menuBar = new JMenuBar();
        JMenu menu1 = new JMenu("menu");
        menuBar.add(menu1);
        JMenuItem menuItem1 = new JMenuItem("Item 1", KeyEvent.VK_1);

        menu1.add(menuItem1);

        menuItem1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            }
        });

        return menuBar;
    }

    public Task1panel () {
        setTitle("GUI");
        setSize(150, 150);

        //The code below creates the two panels of the UI And they are both labelled with names.
        JPanel jsp1 = new JPanel();
        JPanel jsp2 = new JPanel();
        JLabel j1 = new JLabel("Left Side");
        JLabel j2 = new JLabel("Right Side");

        //jsp1 and jsp2 work together with the code above to create the two panels of the interface by adding "J1" and "J2" this allows 
        //both sides to be labelled and appear on the UI        
        jsp1.add(j1);
        jsp2.add(j2);   

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, jsp1, jsp2);

        splitPane.setOneTouchExpandable(true);
        getContentPane().add(splitPane);
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // build and show your GUI               
                Task1panel sp = new Task1panel ();
                sp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                sp.setVisible(true);
            }
        });
    }
}

此代码中没有错误,一切都应该有效,但似乎没有任何工作。

1 个答案:

答案 0 :(得分:0)

您似乎错过了对setJMenubar(setupMenu());的来电,实际上,setMenu()未被调用。

Task1panel构造函数的末尾,尝试按照以下示例中的操作添加调用:

Task1panel () {
     //...
     setJMenubar(setupMenu());
}