You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java运行时动态修改JFrame属性报错求助

Fix for JFrame Visibility Modification Error

Why the Error Occurs

  1. Missing JFrame Reference: F_3x3 is likely defined in another class, and WinnerClass doesn't hold a valid, accessible reference to it—either it's out of scope, or you haven't passed the instance to WinnerClass.
  2. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 11:31:01