Java Swing:JLabel 文本未出现在屏幕上

Java Swing: JLabel Text Not Appearing on Screen

我正在尝试从 Scanner 获取名称输入并通过 JLabel 在屏幕上显示。但是,它没有出现。我制作的按钮出现了,但标签没有出现。我错过了什么吗?

import javax.swing.*;
import java.awt.*; 
import java.util.*; 
import java.lang.*; 

public class MyProgram {
   
    public static void main(String[] args) {
        //creating instance of JFrame
        
        JFrame f= new JFrame();
        JButton b1 = new JButton("Generate Password");
        b1.setBounds(90, 100, 180, 40);
        f.add(b1);
        b1.setBackground(Color.RED);
        b1.setOpaque(true);
        f.setSize(500, 500);
        f.setLayout(null);
        f.setVisible(true);
        Scanner sc = new Scanner(System.in);
        System.out.println("What is your name?"); 
        String name = sc.nextLine(); 
        JLabel n = new JLabel(); 
        n.setBounds(400, 100, 30, 30);
        n.setText(name + "'s Password Generator!");
        f.add(n);
    }
}
  1. 您将 GUI- 与 Console-Application 混合在一起。这真的是你想要的吗?
  2. 您是 nullingJFrame 的布局。你为什么这么做?你基本上总是需要布局。查看 this 指南。

您的 JLabel 确实显示了。输入您的名字后尝试调整 JFrame 的大小,然后您应该会看到 JLabel。如果在程序结束时调用 setVisible(true)JLabel 将始终出现。这是因为你的 JFrame 在你调用 setVisible(true) 时被绘制了。如果向其添加另一个组件,则 JFrame 不会重新绘制。如果调整它的大小,它将被重新绘制。

但是,您应该看看 basic Java Swing tutorials