簡體   English   中英

Java JLabel不顯示

[英]Java JLabel does not show up

JLabel沒有顯示! 當我單擊frame時,僅顯示buttons() 是否可以不單擊顯示它?

public frame() {
    frame.setTitle("MyWindowTitle");
    frame.setSize(width, height);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.setResizable(true);
    // frame.setLayout(new FlowLayout());
    frame.setLayout(null);
    frame.getContentPane().setBackground(Color.RED);
    frame.pack();
    frame.setVisible(true);
    JPanel panel = new JPanel();
    frame.add(panel);
    panel.setLocation(150, 150);
    panel.add(new JButton("Hello!"));
    scorel = new JLabel("Score: " + score);
    frame.add(scorel);

    buttons();
}

使

 //frame.pack(); //Dont call pack() if you use null layout
 frame.setVisible(true);

是方法的最后一個語句。 並且還使用panel setSize() ,因為在frame使用null layout 如果沒有setSizesetLocation或一起使用setBounds ,則您的內容將無法正確顯示為null layout

panel.setSize(400, 300);

scorel.setSize(width, height);
scorel.setLocation(x, y);

良好作法

  1. 盡量避免空布局

    要了解布局,請訪問https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

  2. 修復您的變量和類名稱樣式。 了解命名約定http://www.oracle.com/technetwork/java/codeconventions-135099.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM