Java 图形用户界面工具栏
我正在开发一个 Java 桌面应用程序。我希望 JFrame 顶部有一些工具栏(就像在通常的 GUI 应用程序中一样)。
我想允许用户通过单击某些按钮动态添加/删除工具栏。我如何实现这一点(通过任何布局或其他方式),以便当用户添加/删除工具栏时,工具栏下方的其余空间会相应调整。
I am developing a Java Desktop Application. In that I want some toolbars at the top of the JFrame (as in usual GUI appllications).
I want to allow user to add/remove toolbars dynamically by clicking on some buttons. How can I implement this (through any Layouts or some other way) so that when a user add/removes a toolbar, the rest of the space below the toolbar is adjusted accordingly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议您在程序中使用 BorderLayout,并保留工具栏的北区。向此(北)区域添加另一个容器(使用 BoxLayout 或 FlowLayout),具体取决于您希望如何添加工具栏/将其放置在容器中的位置。
请查看此 Java 布局管理器教程。
I would recommend you using BorderLayout for the program and keep the North area for the toolbars. To this (North) area add another container (with BoxLayout or FlowLayout), depending on how you want your toolbars to be added/where placed in the container.
Have a look at this Java Layout Manager tutorial.
如果您使用正确的 LayoutManager 并添加/删除组件,则应自动计算布局。
现在,如果您稍后执行类似
我认为(但尚未测试)的操作,面板将自动重新布局以匹配新配置。
If you use the correct LayoutManager and add/remove the components, the layout should be computed automatically.
Now if you later execute something like
I think (but haven't tested) that the panel will automatically relayout itself to match the new configuration.
我通过为所有工具栏创建一个 JPanel(为该 JPanel 设置“框”布局),将我的 JToolBar 工具栏放在 JPanel 上,并将我的按钮放在各自的 JToolBar 上对它们进行分组,最终使我的工具栏正常工作。我使用的是 NetBeans,它会生成代码,因此我无法有效地将代码放在这里。
通过该设置,我可以使用 setVisible() 方法来显示和隐藏各个按钮和 JToolBar。文档指出应该使用 validate() 方法来重新定位按钮,但它对我来说没有它也有效,至少在 Windows 7 下是这样。当我在 Ubuntu 10 下尝试时,工具栏的布局是错误的,所以我的答案目前部分正确。
I got my toolbar to finally work by making a JPanel for all the toolbars (setting the "box" layout for that JPanel), putting my JToolBar toolbars on the JPanel, and putting my buttons on their respective JToolBar to group them. I'm using NetBeans, which generates the code, so I can't effectively put the code here.
With that setup, I can use the setVisible() method to show and hide individual buttons and JToolBar's. The documentation states that the validate() method should be used to reposition the buttons, but it works for me without it, at least under Windows 7. When I tried it under Ubuntu 10, the layout of the toolbar was wrong, so my answer is partially correct for now.