Java运行时动态修改JFrame属性报错求助
Fix for JFrame Visibility Modification Error
Why the Error Occurs
- Missing JFrame Reference:
F_3x3is likely defined in another class, andWinnerClassdoesn't hold a valid, accessible reference to it—either it's out of scope, or you haven't passed the instance toWinnerClass. - EDT Violation: Swing components must be modified on the Event Dispatch Thread (EDT). Changing visibility outside this thread can trigger runtime errors or unstable UI behavior.
Step-by-Step Solution
1. Pass the JFrame Instance to WinnerClass
Add a member variable in WinnerClass to store the JFrame reference, and initialize it via a constructor.
2. Wrap UI Changes in the EDT
Use SwingUtilities.invokeLater() to ensure the visibility modification runs on the correct thread.
Corrected Code
import javax.swing.SwingUtilities; import javax.swing.JFrame; public class WinnerClass { private JFrame gameFrame; // Constructor to accept the target JFrame public WinnerClass(JFrame targetFrame) { this.gameFrame = targetFrame; } public void RunEnd(short who) { System.out.format("Player %d wins", who); // Safely update UI on the Event Dispatch Thread SwingUtilities.invokeLater(() -> { gameFrame.setVisible(false); }); } public boolean win3x3(short who) { // Simplified return logic return ((mat9[0] == who && mat9[1] == who && mat9[2] == who) || (mat9[0] == who && mat9[4] == who && mat9[8] == who)); } }
Implementation Example
In the class where F_3x3 is defined, initialize WinnerClass with your JFrame instance:
// Pass your JFrame to WinnerClass WinnerClass winnerHandler = new WinnerClass(F_3x3); // Call RunEnd when a winner is detected winnerHandler.RunEnd(winningPlayer);
Content from stack exchange, asked by Arash
相关产品推荐
相关产品推荐

