我正在使用扩展 JFrame 的自定义类,但有时它什么也不显示。我从来没有遇到过任何错误,所以我很好奇这是否是一个可以帮助我打印某些东西的 java 命令。我环顾四周寻找其他问题,但没有发现任何相似之处。并没有真正做任何太疯狂的事情,但很好奇为什么会这样。我想更正问题以避免将来出现问题。
空白
界面
public MemberPanel(int i) throws IOException {
Container contentPane = getContentPane();
GridLayout layout = new GridLayout(2, 1);
contentPane.setLayout(layout);
setVisible(true);
setLocation(0, 0);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(640, 170);
setResizable(false);
greenStatus = new JButton("Non-Critical");
yellowStatus = new JButton("Important");
redStatus = new JButton("Mission Critical");
greenStatus.setFont(fontTextOne);
yellowStatus.setFont(fontTextOne);
redStatus.setFont(fontTextOne);
greenStatus.addActionListener(this);
yellowStatus.addActionListener(this);
redStatus.addActionListener(this);
buttonPanel.add(greenStatus);
buttonPanel.add(yellowStatus);
buttonPanel.add(redStatus);
statusLabel = new JLabel("In 75 letters or less... What are you working on?");
statusLabel.setVerticalAlignment(JLabel.CENTER);
statusLabel.setHorizontalAlignment(JLabel.CENTER);
statusLabel.setFont(fontTextTwo);
textFieldPanel.add(statusLabel);
textFieldPanel.add(statusMessage);
contentPane.add(buttonPanel);
contentPane.add(textFieldPanel);
}
最佳答案
在调用 JFrame 上的 setVisible(true)
后,您添加了一堆组件:
public MemberPanel(int i) throws IOException {
Container contentPane = getContentPane();
GridLayout layout = new GridLayout(2, 1);
contentPane.setLayout(layout);
setVisible(true); // ****** here
// .....
// only now do you add components...
contentPane.add(buttonPanel);
contentPane.add(textFieldPanel);
}
因此组件可能会或可能不会显示,具体取决于 GUI 是否重绘(看看当您重新调整空 gui 的大小时会发生什么)。修复:仅在添加所有内容后调用setVisible(true)
。
关于Java GUI 编译没有错误,但有时什么都不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9952026/