javaSwing如何创建一个有工具条和菜单的窗口

javaSwing如何创建一个有工具条和菜单的窗口,第1张

代码如下:

public class App extends JFrame {

 

    public App() {

         

        this.setSize(400, 400)

        this.setLocationRelativeTo(null)

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

        

        // 添加菜单

        JMenuBar menuBar = new JMenuBar()

        this.setJMenuBar(menuBar)

        

        JMenu menu = new JMenu("文件")

        menuBar.add(menu)

        

        JMenuItem testMenuItem = new JMenuItem("打开")

        testMenuItem.addActionListener(e -> JOptionPane.showMessageDialog(this, "打开"))

        menu.add(testMenuItem)

        

        // 添加工具栏

        JToolBar toolBar = new JToolBar()

        this.add(toolBar, BorderLayout.NORTH)

        

        JButton btnSave = new JButton("保存")

        btnSave.addActionListener(e -> JOptionPane.showMessageDialog(this, "保存"))

        toolBar.add(btnSave)

    }

     

    public static void main(String[] args) {

       new App().setVisible(true)

    }

}

运行结果:

这很简单。

首先你需要创建一个JFrame,或者它的子类的实例。

接着,新建一个JMenuBar, 加入你需要的JMenu。JMenu里面也可以套JMenu,也可以套JMenuItem。

最后,frame里面

frame.setJMenuBar(jmenubar)

JPanel jp = new JPanel()

JMenuBar jmb = new JMenuBar()

jp.add(jmb)

你用图形界面编程的话直接把组件拖上去,会默认用getContent()的,是可以显示的,可能是你没有处理好吧


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11931699.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-19
下一篇 2023-05-19

发表评论

登录后才能评论

评论列表(0条)

保存