[英]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);
}
}
nulling
JFrame
的 Layout 。 你为什么这么做? 你基本上总是需要布局。 看看这个指南。 您的JLabel
确实在显示。 输入您的姓名后尝试调整JFrame
大小,然后您应该会看到您的JLabel
。 如果您在程序结束时调用setVisible(true)
, JLabel
将始终出现。 这是因为当您调用setVisible(true)
时,您的JFrame
会被绘制。 如果向其中添加另一个组件,则不会重新绘制JFrame
。 如果您调整它的大小,它将被重新绘制。
但是,您应该查看基本的 Java Swing 教程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.