问题
I have a class that creates a JFrame. When the JFrame is created it has a start button. 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?
回答1:
In order to acheive this you have to pass the reference of JFrame using this keyword.
回答2:
To have access to a private instance within another class, I think you should use agetter. Example:
//JFrame declaration
private JFrame frame;
//Getter
public JFrame getFrame() {
return frame;
}
回答3:
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:
- Always be sure to make Swing state changes on the Swing event thread (the EDT). 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
- your SwingWorker can notify observers of change via PropertyChangeListeners and "bound" properties, or
- if using a standard Thread/Runnable, you will need to be sure to queue Swing calls onto the EDT using
SwingUtilities.invokeLater(someRunnable)
- 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.
- 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.
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.
来源:https://stackoverflow.com/questions/29149798/access-java-jframe-from-another-class