简体   繁体   English

从另一个类访问Java JFrame

[英]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类传递到另一个类的构造函数参数中,并使用该参数设置字段,但是需要注意的是:

  • Always be sure to make Swing state changes on the Swing event thread (the EDT). 始终确保在Swing事件线程(EDT)上更改Swing状态。 Since you're using background threading, this means that you will either 由于您使用的是后台线程,因此您将可以
    • use a SwingWorker as your background thread, and notify the GUI of changes via the publish/process method pair, or 使用SwingWorker作为后台线程,并通过发布/处理方法对通知GUI更改,或者
    • your SwingWorker can notify observers of change via PropertyChangeListeners and "bound" properties, or 您的SwingWorker可以通过PropertyChangeListener和“绑定”属性将更改通知给观察者,或者
    • if using a standard Thread/Runnable, you will need to be sure to queue Swing calls onto the EDT using SwingUtilities.invokeLater(someRunnable) 如果使用标准Thread / Runnable,则需要确保使用SwingUtilities.invokeLater(someRunnable)将Swing调用SwingUtilities.invokeLater(someRunnable) EDT。
  • Even better is to use a Model-View-Control type structure, but even if you do this, the model should be changed on the EDT for the same reasons above. 更好的方法是使用Model-View-Control类型结构,但是即使您这样做,出于上述相同原因,也应该在EDT上更改模型。
  • As a side recommendation in general I try to avoid making classes that extend JFrame as that unnecessarily restricts my code to creating just JFrames. 作为一般建议,我尽量避免创建扩展JFrame的类,因为这不必要地将我的代码限制为仅创建JFrames。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM