[英]Java Swing: JLabel Text Not Appearing on Screen
I'm trying to get a name input from the Scanner
and display that on the screen through a JLabel
.我正在尝试从Scanner
获取名称输入并通过JLabel
将其显示在屏幕上。 However, it is not appearing.但是,它没有出现。 The button that I made appears, but the label does not.我制作的按钮出现了,但标签没有。 Am I missing something?我错过了什么吗?
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
the Layout of your JFrame
.您正在nulling
JFrame
的 Layout 。 Why do you do this?你为什么这么做? You basically always need layouting.你基本上总是需要布局。 Have a look at this guide.看看这个指南。 Your JLabel
is indeed showing.您的JLabel
确实在显示。 Try to resize your JFrame
after you typed in your name, you should see your JLabel
then.输入您的姓名后尝试调整JFrame
大小,然后您应该会看到您的JLabel
。 The JLabel
will always appear, if you call setVisible(true)
at the end of your program.如果您在程序结束时调用setVisible(true)
, JLabel
将始终出现。 This is because your JFrame
gets painted when you call setVisible(true)
.这是因为当您调用setVisible(true)
时,您的JFrame
会被绘制。 If you add another component to it, the JFrame
is not repainted.如果向其中添加另一个组件,则不会重新绘制JFrame
。 If you resize it, it will be repainted.如果您调整它的大小,它将被重新绘制。
However, you should have a look at basic Java Swing tutorials .但是,您应该查看基本的 Java Swing 教程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.