[英]Access Java JFrame from another class
I have a class that creates a JFrame. 我有一个创建JFrame的类。 When the JFrame is created it has a start button. 创建JFrame时,它具有一个开始按钮。 When the start button is clicked, it runs two threads until the stop button is clicked. 单击开始按钮时,它将运行两个线程,直到单击停止按钮。 The two threads are in another class file. 这两个线程在另一个类文件中。 From the class that contains the threads, how can I access the JFrame instance in order to change value that are displayed? 从包含线程的类中,如何访问JFrame实例以更改显示的值?
为了达到这个目的,您必须使用此关键字传递JFrame的引用。
To have access to a private instance within another class, I think you should use agetter. 要访问另一个类中的私有实例,我认为您应该使用agetter。 Example: 例:
//JFrame declaration
private JFrame frame;
//Getter
public JFrame getFrame() {
return frame;
}
As noted by one answer, you can pass in a reference of the GUI or view into any class that needs it, for instance by passing the GUI class into the other class's constructor parameter, and using the parameter to set a field, but having said that, there are caveats: 正如一个答案所指出的,您可以传入GUI的引用或视图到需要它的任何类中,例如,将GUI类传递到另一个类的构造函数参数中,并使用该参数设置字段,但是需要注意的是:
SwingUtilities.invokeLater(someRunnable)
如果使用标准Thread / Runnable,则需要确保使用SwingUtilities.invokeLater(someRunnable)
将Swing调用SwingUtilities.invokeLater(someRunnable)
EDT。 Note that this help is very general, but if you need more specific help, then you will want to post more specific information regarding your problem and your pertinent code. 请注意,此帮助非常笼统,但是如果您需要更具体的帮助,则需要发布有关您的问题和相关代码的更具体的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.