当我将 JLabel(标题文本)添加到 JPanel(标题背景)时,标题文本有时只会在运行该类后出现。按类编译器的结果显示这两张图片之一( vs ),而我根本没有更改代码。
如何修复“锻造英雄”文本始终出现的位置?
import java.awt.Color; //For background color in JFrame
import java.awt.Container;
import java.awt.Font;
import javax.swing.JFrame; //For JFrame
import javax.swing.JLabel;
import javax.swing.JPanel;
public class game
{
JFrame window = new JFrame("Forging Hero");
Container con; //A base over JFrame, can put things on it, allows adding icons and words on
JPanel titleNamePanel;
JLabel titleNameLabel; //Displays text
Font titleFont = new Font("Time New Roman", Font. BOLD, 28); //Font for the title text
public static void main(String[] args)
{
new game();
}
public game()
{
window = new JFrame();
window.setSize(800, 600);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(Color.black);
window.setLayout(null);
window.setVisible(true);
window.setTitle("Forging Hero");
con = window.getContentPane();
titleNamePanel = new JPanel();
titleNamePanel.setBounds(100, 100, 600, 150); //Starts from top left: x, y, width, height
titleNamePanel.setBackground(Color.magenta);
titleNameLabel = new JLabel("Forging Hero");
titleNameLabel.setForeground(Color.white);
titleNameLabel.setFont(titleFont);
titleNamePanel.add(titleNameLabel); //Adds text from JLabel onto the JPanel
con.add(titleNamePanel);
}
}
您应该只在所有内容都添加到 JFrame 后调用
window.setVisible(true);
。否则,除非您手动调用重绘,否则您无法保证窗口何时刷新/重绘。
因此,要解决您的问题,请将
window.setVisible(true);
移动到 game
方法的最后,如下所示:
public game()
{
window = new JFrame();
window.setSize(800, 600);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(Color.black);
window.setLayout(null);
window.setTitle("Forging Hero");
...
titleNamePanel.add(titleNameLabel);
con.add(titleNamePanel);
//Call this rigt at the end
window.setVisible(true);
}
否则,如果您更新了 swing 组件/容器的内容,您通常需要调用
component.repaint();
。在这种情况下,您可以在 game
末尾执行此操作,而不是强制刷新 JFrame 内容:
public game()
{
...
titleNamePanel.add(titleNameLabel);
con.add(titleNamePanel);
//Call this rigt at the end
window.repaint();
}