JFrame 缺少内容 GridBagLayout 与面板
JFrame Missing Contents GridBagLayout with Panels
我在 OSX 上使用 NetBeans 8.2,当我 运行 我的代码时,我得到一个具有正确标题的 window,但没有出现任何组件。我确保我所有的框架都设置为可见,但问题仍然存在。
public Project(){
setTitle("Panel");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
setLayout(new GridBagLayout());
setVisible(true);
GridBagConstraints layout = new GridBagConstraints();
layout.gridy = 3;
JPanel topPanel = new JPanel();
topPanel.setVisible(true);
topPanel.setLayout(new GridLayout(2,1));
topPanel.add(label1);
topPanel.add(textField1);
JPanel midPanel = new JPanel();
midPanel.setVisible(true);
midPanel.setLayout(new GridLayout(1,1));
midPanel.add(button1);
JPanel bottomPanel = new JPanel();
bottomPanel.setVisible(true);
bottomPanel.setLayout(new GridLayout(2,1));
bottomPanel.add(label2);
bottomPanel.add(textField2);
add(topPanel);
add(midPanel);
add(bottomPanel);
}
public static void main(String[] args) {
Project1 frame = new Project1();
}
采用 setVisible(true);
并使其成为您可以在构造函数中调用的最后一件事
public Project(){
setTitle("Panel");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
setLayout(new GridBagLayout());
//setVisible(true);
//...
setVisible(true);
}
您还应该确保 UI 是在事件调度线程
的上下文中构建的
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Project1 frame = new Project1();
}
});
}
这将有助于防止可能发生的一些奇怪情况
我在 OSX 上使用 NetBeans 8.2,当我 运行 我的代码时,我得到一个具有正确标题的 window,但没有出现任何组件。我确保我所有的框架都设置为可见,但问题仍然存在。
public Project(){
setTitle("Panel");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
setLayout(new GridBagLayout());
setVisible(true);
GridBagConstraints layout = new GridBagConstraints();
layout.gridy = 3;
JPanel topPanel = new JPanel();
topPanel.setVisible(true);
topPanel.setLayout(new GridLayout(2,1));
topPanel.add(label1);
topPanel.add(textField1);
JPanel midPanel = new JPanel();
midPanel.setVisible(true);
midPanel.setLayout(new GridLayout(1,1));
midPanel.add(button1);
JPanel bottomPanel = new JPanel();
bottomPanel.setVisible(true);
bottomPanel.setLayout(new GridLayout(2,1));
bottomPanel.add(label2);
bottomPanel.add(textField2);
add(topPanel);
add(midPanel);
add(bottomPanel);
}
public static void main(String[] args) {
Project1 frame = new Project1();
}
采用 setVisible(true);
并使其成为您可以在构造函数中调用的最后一件事
public Project(){
setTitle("Panel");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocationRelativeTo(null);
setLayout(new GridBagLayout());
//setVisible(true);
//...
setVisible(true);
}
您还应该确保 UI 是在事件调度线程
的上下文中构建的public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Project1 frame = new Project1();
}
});
}
这将有助于防止可能发生的一些奇怪情况