更新一个类的Jpanel

发布于 2024-08-26 20:49:49 字数 288 浏览 5 评论 0原文

在使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧伤还要旧人安 2024-09-02 20:49:49

只要您有对 JPanel 的引用,您就可以通过在 JPanel 上调用 add(JComponent comp) 来添加您想要的任何 GUI 元素。

所以,你可以做这样的事情:

class Panel extends JPanel{

    ...    

}

class Main{

    public Main(JPanel thePanel){
        thePanel.add(new JButton("Hello"));
    }
}

这是你正在寻找的吗?

如果您在类中设置了公共访问器方法,您还可以更新从另一个类添加到面板的字段。因此,在您的 panel 类中,您有一个方法:

public JButton getButton(){
    return button;
}

然后您可以通过引用您的面板类从任何类访问该按钮,如下所示:

panel.getButton().setText("Some text");

请注意,该按钮也可以是公共的,然后您可以直接直接调用该方法: 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:

class Panel extends JPanel{

    ...    

}

class Main{

    public Main(JPanel thePanel){
        thePanel.add(new JButton("Hello"));
    }
}

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:

public JButton getButton(){
    return button;
}

Then you can access the button from whatever class with a reference to your panel class, like this:

panel.getButton().setText("Some text");

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文