JMenuBar 可见性混乱
JMenuBar visibility confusion
我正在 Java 学习 GUI。
我在这里有点困惑。当我像这样放置 window.setVisible(true);
时,如果我调整它的大小,我只会看到 JMenuBar(如果没有某种交互,它不会显示)。
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class Main {
public static void main(String[] args) {
JFrame window = new JFrame("My App");
window.setSize(500, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
JMenuBar bar = new JMenuBar();
window.setJMenuBar(bar);
JMenu menu = new JMenu("File");
bar.add(menu);
}
}
但是当我把它放在最底部时,它显示如预期。这是为什么?
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class Main {
public static void main(String[] args) {
JFrame window = new JFrame("My App");
window.setSize(500, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar bar = new JMenuBar();
window.setJMenuBar(bar);
JMenu menu = new JMenu("File");
bar.add(menu);
window.setVisible(true);
}
}
这里说明了必须在最后调用,请问这是什么原因呢?
java JMenuBar not visible?Why?
添加组件后,您必须重新绘制容器。
因此,如果您在 window 可见后添加菜单栏,它将在下次重绘后弹出,在您的示例中,在调整大小后弹出。如果在设置 window 之前添加菜单栏可见,它将在第一次绘制时被绘制。
这是 Swing 组件的常见行为。
如果您添加或删除组件:
If the container has already been displayed, the hierarchy must be
validated thereafter in order to display the added component.
我正在 Java 学习 GUI。
我在这里有点困惑。当我像这样放置 window.setVisible(true);
时,如果我调整它的大小,我只会看到 JMenuBar(如果没有某种交互,它不会显示)。
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class Main {
public static void main(String[] args) {
JFrame window = new JFrame("My App");
window.setSize(500, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
JMenuBar bar = new JMenuBar();
window.setJMenuBar(bar);
JMenu menu = new JMenu("File");
bar.add(menu);
}
}
但是当我把它放在最底部时,它显示如预期。这是为什么?
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
public class Main {
public static void main(String[] args) {
JFrame window = new JFrame("My App");
window.setSize(500, 500);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar bar = new JMenuBar();
window.setJMenuBar(bar);
JMenu menu = new JMenu("File");
bar.add(menu);
window.setVisible(true);
}
}
这里说明了必须在最后调用,请问这是什么原因呢?
java JMenuBar not visible?Why?
添加组件后,您必须重新绘制容器。 因此,如果您在 window 可见后添加菜单栏,它将在下次重绘后弹出,在您的示例中,在调整大小后弹出。如果在设置 window 之前添加菜单栏可见,它将在第一次绘制时被绘制。
这是 Swing 组件的常见行为。
如果您添加或删除组件:
If the container has already been displayed, the hierarchy must be validated thereafter in order to display the added component.