更新一个类的Jpanel
在使用 jpanel 的一些建议之后 - 我是 java 新手并且正在尝试使用 GUI 元素。
基本上我很好奇的是,我是否可以在一个类中设置一个 Jpanel,然后以某种方式向该容器添加标签等,但来自另一个类。
这可能吗?或者我是否必须在一个类中设置整个 GUI,但是如果我想从另一个类更新我在主类中设置的那些字段,我想我会遇到同样的问题?
抱歉,我真的没有任何可以在这里演示的有用代码 - 我只是想让这个想法继续下去,在继续之前弄清楚它是否可能。我什至不确定这是否可能。任何建议将不胜感激。
谢谢
After some advice on using jpanel - I'm new to java and playing around with the GUI elements.
Bascially what I'm curious about is if I can set up a Jpanel in one class, then somehow add labels etc to the that container, but from another class.
Is this possible ? or do i have to set the entire GUI up in one class, but then I guess I would have the same issue, if I wanted to update those fields I had set up in the main class from another class?
Apologies I don't really have any code that's usefull to demostrate here - I'm just trying to get the idea going, working out if its possible before I go ahead. And I'm not even sure if this is possible. Any advice would be greatly appreciated.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只要您有对 JPanel 的引用,您就可以通过在 JPanel 上调用
add(JComponent comp)
来添加您想要的任何 GUI 元素。所以,你可以做这样的事情:
这是你正在寻找的吗?
如果您在类中设置了公共访问器方法,您还可以更新从另一个类添加到面板的字段。因此,在您的
panel
类中,您有一个方法:然后您可以通过引用您的面板类从任何类访问该按钮,如下所示:
请注意,该按钮也可以是公共的,然后您可以直接直接调用该方法:
panel.button.setText("Some text");
但这不被认为是好的代码,因为它违反了一些一般的良好 OOP 实践,这里不予提及。As long as you have a reference to the JPanel, you can add whatever GUI-element you want, by calling
add(JComponent comp)
on the JPanel.So, you can do something like this:
Was this what you were looking for?
You can also update the fields added to the panel from another class, if you have a public accessor-method set up, in the class. So in your
panel
class, you have a method:Then you can access the button from whatever class with a reference to your panel class, like this:
Note that the button could just as well be public, then you could simply call the method directly:
panel.button.setText("Some text");
but this is not considered good code, as it violates some general good OOP practices, not relevant to mention here.