简体   繁体   English

GUI 无法将 () JLabel 添加到 JFrame

[英]GUI cannot add() JLabel to the JFrame

I am just new to Java.我只是 Java 的新手。 When I run the program below I get nothing - no JLabel is added to the window当我运行下面的程序时,我什么也没得到 - 窗口中没有添加JLabel

  import javax.swing.JFrame;
  import javax.swing.JLabel;
  import java.awt.FlowLayout;

  public class MainProgram{

  public static void main(String[] args) {
    JFrame frame = new JFrame("This is the title of the window");//adding the JFrame or window
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//so it really and literally close when we 
    //hit the close button on the window
    frame.setVisible(true);//setting the visibility
    //adding the label
    JLabel label_1 = new JLabel("this is a JLabel");
    //adding the label to the window
    label_1.setToolTipText("This is the tool tip");
    add(label_1);
}
}

Any suggestions?有什么建议吗?

First of all, this is wrong code.首先,这是错误的代码。

public class MainProgram extends { // extends What?

But, what you are doing wrong is that you are adding the JLabel to whatever you extend, and not to your frame .但是,您做错的是将 JLabel 添加到您扩展的任何内容,而不是添加到您的frame So, change this line:所以,改变这一行:

add(label_1);

to

frame.add(label_1);

You need add your component to your frame frame.add(label_1);您需要将您的组件添加到您的框架frame.add(label_1); and set the dimension of your frame并设置框架的尺寸

just add this line只需添加这一行

frame.pack(); 

try to set a dimension to the jlabel and the frame itself;尝试为 jlabel 和框架本身设置尺寸; when using add(Component) don't to forget frame before it, use it as following : frame.add(yourLabel);使用 add(Component) 时不要忘记之前的 frame,使用如下: frame.add(yourLabel);

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

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