我有一个简单的文本程序,正在加载带有 2 个 JPanel(正文和页脚)的 jframe,一个正文区域的文本区域和页脚的标签。我不确定我的订单是否错误或者我忘记了什么,但启动程序时出现延迟,导致它闪烁白色。这有点烦人,如果可能的话我想避免这种情况。有什么想法吗?
它应该是这样的,但一开始它会闪烁白色并闪烁半秒。 我也尝试将框架背景设置为蓝色,但这并没有改变任何东西。
JFrame frame = new JFrame("SIMPLE TEXT");
JPanel panel = new JPanel();
JTextArea textarea = new JTextArea();
JPanel footer = new JPanel();
JLabel linecol = new JLabel("line: 0 col: 0");
frame.setSize(640,480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setResizable(false);
panel.setSize(frame.getBounds().width, frame.getBounds().height);
panel.setBackground(bgColor);
panel.setForeground(fgColor);
panel.setLayout(new BorderLayout());
footer.setSize(640,20);
footer.setBackground(bgColor);
footer.setLayout(new BorderLayout());
footer.setBorder(new EmptyBorder(0,0,0,10));
textarea.setSize(400, 400);
textarea.setOpaque(false);
textarea.setForeground(fgColor);
textarea.setCaretColor(fgColor);
linecol.setForeground(fgColor);
frame.add(panel);
panel.add(footer, BorderLayout.PAGE_END);
panel.add(textarea);
footer.add(linecol, BorderLayout.LINE_END);
将其
frame.setVisible(true);
移至屏幕构建后调用的列表命令
JFrame frame = new JFrame("SIMPLE TEXT");
JPanel panel = new JPanel();
JTextArea textarea = new JTextArea();
JPanel footer = new JPanel();
JLabel linecol = new JLabel("line: 0 col: 0");
//frame.setSize(640,480);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setLocationRelativeTo(null);
//frame.setVisible(true);
//frame.setResizable(false);
//...
frame.add(panel);
panel.add(footer, BorderLayout.PAGE_END);
panel.add(textarea);
footer.add(linecol, BorderLayout.LINE_END);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
您还会发现,使用
setSize
来尝试调整组件大小是毫无意义的(并且强烈建议不要这样做),因为框架和面板是在布局管理器的控制下......
另请注意,
setResizable
可以更改框架边框的大小,在尝试调整窗口大小和/或位置之前需要调用它。
已更新
JTextArea(int, int)
向布局管理器提供大小调整提示。如果您将其放在 JTextArea
中,您可能还会发现 JScrollPane
更有用。请参阅如何使用滚动窗格了解更多详细信息
即使在组件设置结束时调用 setVisible(true),您仍然可能会遇到最初的白色闪烁。因为您的内容可能有一些具有不同持续时间和计时的 EDT 线程操作
更安全的方法是使用 SwingUtilities.invokeLater() 来确保 setVisible(true) 在所有 GUI 操作完成后执行:
// Initialize and set up your frame and components
JFrame frame = new JFrame("Your Frame Title");
// Configuration and component adding code here
// Delay setting the frame visible to avoid initial white blink
javax.swing.SwingUtilities.invokeLater(() -> {
frame.setVisible(true);
});