Swing 中的复合模式
这基本上是一个架构问题。
我想在处理 Swing 组件时实现复合模式;也就是说,我想将多个组件与其侦听器和单个组件背后的逻辑组合起来,以便于处理。
例如,考虑一个简单的目录浏览器;比如说,JScrollPane 中的 JTree 具有一些逻辑,可以在用户展开 JTree 节点时处理填充文件名。你会如何实施?
您是否扩展 JScrollPane 并在构造函数中添加 JTree 等,然后您的应用程序处理 JScrollPaneExtended 类?或者您是否扩展 JPanel 或 JComponent?或者,您是否在填充 JFrame 时调用的方法中将所有这些类缝合在一起?还是别的什么?为什么?
我基本上是在寻找其他人使用的粗略指南;显然,我想处理某种形式的 JComponent,以便在构建 GUI 时更容易处理,但是不知何故,仅仅为了有地方放置粘合代码而扩展最顶层的组件(本例中的 JScrollPane)感觉不太合适。
This is basically a architectural question.
I want to implement composite pattern in handling Swing components; that is, I want to combine several components with their listeners and logic behind a single component for easier handling.
Consider for example a simple directory browser; say, a JTree in JScrollPane with some logic which handles populating filenames as user expands JTree nodes. How would you implement that?
Do you extend JScrollPane and add JTree and so on in constructor, and then your application deals with JScrollPaneExtended class? Or do you extend, say, JPanel or JComponent? Or do you stitch all those classes together in a method you call when you're populating your JFrame? Or something else? And why?
I'm basically looking for a rough guideline on what others use; I'd obviously like to deal with some form of JComponent for easier handling in constructing GUI, however somehow it doesn't feel right to extend topmost component (JScrollPane in this example) just to have someplace to put glue code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您不需要 UI 委托,请扩展 < code>JComponent 是罚款;如果您这样做,如何编写自定义 Swing 组件 是一个好的开始。在树表的特定情况下,您可能需要查看
org.netbeans.swing.outline
,如本 答案。If you don't need a UI delegate, extending
JComponent
is fine; if you do, How to Write a Custom Swing Component is a good start. In the particular case of a tree-table, you might want to look atorg.netbeans.swing.outline
, as discussed in this answer.我对一个专有的 swing 应用程序正是这样做的,它使用单独且并行的类层次结构,其中一个“组件”类包装一个或多个 JComponent。我需要一个基类来执行许多常见的操作(例如从 XML 文件设置属性),因此扩展
JComponent
不是一个选项。对于文本字段和按钮等简单的小部件,我的组件类仅包含一个小部件。对于任何可能滚动的内容(表格、列表、面板),我的组件在功能小部件顶部有一个 JSrollPane。我还有一个“组”组件,用于处理一组复选框或单选按钮。
设置起来需要一些努力,但是一旦您具备了基本设施,添加新的小部件就非常容易。
I did exactly that for a proprietary swing app using a separate and parallel class hierarchy, with one "component" class wrapping one or several
JComponent
s. I need a base class to do lots of common stuff (e.g. setting properties from an XML file) so extendingJComponent
is not an option.For simple widgets like text field and button, my component class simply contains one widget. For anything that may scroll (table, list, panel), my component has a
JSrollPane
on top of the functional widget. I also have a "group" component that deals with a group of check boxes or radio buttons.It takes some efforts to set up, but once you have the basic facilities, it's very easy to add new widgets.