java JLabel 不显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16360418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JLabel doesn't show up
提问by James L.
I'm working on a program but my JLabel doesn't show up. My JButton works perfectly (it appears) but for some reason the JLabel does not appear. I have checked on internet but I Haven't found anything.
我正在开发一个程序,但我的 JLabel 没有出现。我的 JButton 工作正常(它出现)但由于某种原因 JLabel 没有出现。我已经在互联网上检查过,但我没有找到任何东西。
package com.hinx.client;
import java.awt.Color;
import javax.swing.*;
public class Main {
public static void main(String [] args)
{
createWindow();
}
static void createWindow()
{
//Create panel
JPanel content = new JPanel();
content.setLayout(null);
//Build the frame
JFrame frame = new JFrame("Hinx - A marketplace for apps - Client ALPHA_0.0.1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700, 400);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.add(content);
frame.setVisible(true);
//Add the login button
JButton login = new JButton("Login");
login.setBounds(0, 342, 150, 30);
//Create login label
JLabel loginlabel = new JLabel("Login Area");
//Create login panel
JPanel loginpanel = new JPanel();
loginpanel.setLayout(null);
loginpanel.setBounds(0, 0, 150, 400);
loginpanel.setBackground(Color.gray);
loginpanel.add(login);
loginpanel.add(loginlabel);
content.add(loginpanel);
}
}
回答by Alexis C.
回答by mKorbel
I have checked on internet but I Haven't found anything.
我已经在互联网上检查过,但我没有找到任何东西。
JFrame is visible before JComponents (
frame.add(content);
) are added / createdmove code line
frame.setVisible(true);
(better everything about JFrame) to the end of constuctor
JFrame 在
frame.add(content);
添加/创建JComponents ( )之前是可见的将代码行
frame.setVisible(true);
(更好的关于 JFrame 的所有内容)移动到构造函数的末尾
回答by Branislav Lazic
Use layouts. FlowLayoutshould be fine in this case. Do not call
setBounds()
and do not set layout as anull
.Add label and button on
JPanel
Then add
JPanel
onJFrame
Call
pack()
instead ofsetSize()
Call
setVisible(true)
in the end.
使用布局。FlowLayout在这种情况下应该没问题。不要调用
setBounds()
并且不要将布局设置为null
.添加标签和按钮
JPanel
然后添加
JPanel
上JFrame
调用
pack()
而不是setSize()
最后打电话
setVisible(true)
。
Good luck!
祝你好运!
回答by Amarnath
You are making setLayout null
.
您正在制作 setLayout null
。
JPanel loginpanel = new JPanel();
loginpanel.setLayout(null);
Use this,
用这个,
JPanel loginpanel = new JPanel();
loginpanel.setLayout(new BorderLayout());
Run the UI on the EDT
instead of running on the main thread. Read this post.
EDT
在主线程上运行 UI而不是在主线程上运行。阅读这篇文章。
Example:
例子:
public static void main(String [] args)
{
Runnable r = new Runnable() {
@Override
public void run() {
createWindow();
}
};
EventQueue.invokeLater(r);
}