在多个框架中使用相同的按钮
我正在学习 Java Swing,我创建了一些 JFrame 窗口,在其中一些窗口中,我创建了一个按钮,它们具有相同的解决方案(例如搜索或保存信息),但是,我一直必须从头开始创建或使用 ctrl+c
ctrl+v
。有没有办法创建一个 JButton 并在多个框架中使用相同的按钮?
对于 JTextfield
来说,有没有一种方法可以只创建一次并用于多个框架?
有一个使用独特按钮并显示“Hello World”的示例吗?
I'm studying Java Swing, and I created some JFrame
windows, in some of them, I created a button and they have the same solution (like search or save information), however, all the time I've had to create from the begining or use ctrl+c
ctrl+v
. Is there a way to create a JButton
and use the same button in multiple frames?
And for JTextfield
, there's a way to create only once and use for multiples frames?
There's an example using a unique button and showing a "Hello World"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Swing 组件只能包含在一个容器中(
JPanel
等)。然而,大多数 Swing 组件都由模型支持,并且这些模型可以轻松地在多个组件实例之间共享。对于JButton
,实际上有两个模型:ButtonModel
和Action
。您可以使用将ActionListener
添加到ButtonModel
中,这应该可以工作。但是,我从未使用过它,因为我更喜欢使用Action
作为按钮。Swing components can only be contained in one container (
JPanel
, etc.). However, most Swing components are backed by models, and those models can easily be shared between multiple component instance. In case ofJButton
there are actually two models: aButtonModel
and anAction
. You can use addActionListener
s to theButtonModel
and that should work. However, I've never used that, since I prefer to useAction
for buttons.嗯,这是可能的,但是有两个副本会简单得多。
要实现它,您需要创建扩展
Component
的委托类,并将所有方法调用传递给按钮的单个实例。不过,您将拥有多个委托实例。
Well it is possible, but it will be much simpler to have two copy.
To achieve it yo need to create delegate class extending
Component
and pass all method calls to single instance of button.You'll have multiple instances of delegate though.