为什么工具栏不显示?我想将其放在“文件/帮助”菜单下...我正在重新创建绘画应用程序,我想将按钮放在工具栏上。菜单工作正常,我相信问题是用户绘制的 Canvas 覆盖了它,但我不确定。请帮忙。
最佳答案
contentPane = new JPanel();
setContentPane(contentPane);
CustomCanvas panel = new CustomCanvas();
panel.setBounds(0, 0, this.getWidth(), this.getHeight());
int xx, yy;
contentPane.add(panel);
contentPane.setLayout(null);
JToolBar toolBar = new JToolBar("This is the toolbar");
toolBar.setBounds(0, 0, 800, 50);
toolBar.setVisible(true);
上面的代码有点困惑,因为:
- 尝试用 JPanel 替换内容面板
- 然后您尝试使用空布局。
- 然后您尝试将组件添加到内容 Pane
最终结果是 CustomCanvas
在工具栏上绘制。
请勿执行上述任何操作。
相反,让内容 Pane 的布局管理器来完成所有工作。 JFrame 的默认布局是 BorderLayout。因此,通常您只需使用:
//contentPane.add(toolBar);
add(toolBar, BorderLayout.PAGE_START);
阅读 Swing 教程中关于 How to Use ToolBars 的部分一个向您展示更好的程序结构的工作示例。
关于java - Java GUI 中不显示工具栏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43643178/