简体   繁体   English

Java JLabel不显示

[英]Java JLabel does not show up

JLabel isn't showing up! JLabel没有显示! The buttons() are only showing when i click in my frame . 当我单击frame时,仅显示buttons() Is it possible to show it without clicking? 是否可以不单击显示它?

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();
}

Make 使

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

is the last statement of your method. 是方法的最后一个语句。 And also use setSize() of panel as you use null layout in frame . 并且还使用panel setSize() ,因为在frame使用null layout Without setSize and setLocation or together setBounds , your content does not properly show in null layout . 如果没有setSizesetLocation或一起使用setBounds ,则您的内容将无法正确显示为null layout

panel.setSize(400, 300);

also

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

Good Practice 良好作法

  1. Try to avoid null layout 尽量避免空布局

    To learn about layout please see https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html 要了解布局,请访问https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

  2. Fix your variable and class name style. 修复您的变量和类名称样式。 Learn naming conventions http://www.oracle.com/technetwork/java/codeconventions-135099.html 了解命名约定http://www.oracle.com/technetwork/java/codeconventions-135099.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM