且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JPanel没有在JFrame中显示 - Java

更新时间:2023-12-05 09:04:34

问题在你提供的代码中并不明显。

The problem is not apparent from the code you have provided.

听起来你想要一些 pack() setSize(int,int) setExtendedState(int)和/或 setResizable( boolean)调用之前的方法 setVisible(true)

It sounds like you want some combination of the pack(), setSize(int,int), setExtendedState(int) and/or setResizable(boolean) methods prior to calling setVisible(true).

编辑:

setTitle(title);
setSize(sizeW, sizeH);
setVisible(visibility);
setResizable(resizability);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

此代码中存在竞争条件。有时主线程会在帧显示之前将组件置于正确的状态;有时框架会在一切准备就绪之前赢得并开始绘画。

There is a race condition in this code. Sometimes the main thread will get the components into the correct state to be painted before the frame displays; sometimes the frame wins and starts painting before everything is ready.

使用Swing的事情是你自动使用多线程代码。虽然初始化主线程上的控件通常是安全的,但是一旦你导致事件调度线程启动(因为 setVisible(true)肯定会所有投注都已关闭。

The thing about using Swing is that you are automatically working with multi-threaded code. Although it is generally safe to initialize controls on the main thread, once you cause the event dispatch thread to start (as setVisible(true) will surely do), all bets are off.

尽可能延迟调用 setVisible(true)。***不要在你的 JFrame 构造函数中调用它。

Delay calling setVisible(true) as long as possible. Preferably, don't call it from within your JFrame constructor.

如果你需要在你之后修改Swing控件已经启动了您的应用程序,您需要通过事件派发线程来执行此操作(请参阅 invokeLater SwingUtilities 方法/ a>,等等。)

If you need to modify Swing controls after you've kicked off your application, you'll need to do it via the event dispatch thread (see the invokeLater and invokeAndWait methods in SwingUtilities, among others).