【问题标题】:When I run this code only the Splitpane shows up but not the JMenu当我运行此代码时,只显示 Splitpane 而不是 JMenu
【发布时间】:2018-04-17 19:26:32
【问题描述】:

当我运行此代码时,界面将被拆分,但是我用来制作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);
            }
        });
    }
}

这段代码没有错误,一切正常,但似乎没有任何工作。

【问题讨论】:

    标签: java jmenu splitpane


    【解决方案1】:

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

    Task1panel 构造函数的末尾,尝试像我在下面的示例中那样添加调用:

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

    【讨论】:

    • 哇,简直不敢相信这就是修复它所需要的一切,感谢您的帮助,感谢您的帮助。
    猜你喜欢
    • 2018-12-09
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    • 2020-10-11
    • 2023-01-16
    • 1970-01-01
    相关资源
    最近更新 更多