Reputation: 141
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.
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);
}
}
Upvotes: 1
Views: 15821
Reputation: 8865
You are making 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.
Example:
public static void main(String [] args)
{
Runnable r = new Runnable() {
@Override
public void run() {
createWindow();
}
};
EventQueue.invokeLater(r);
}
Upvotes: 2
Reputation: 14826
Use layouts. FlowLayout should be fine in this case. Do not call setBounds()
and do not set layout as a null
.
Add label and button on JPanel
Then add JPanel
on JFrame
Call pack()
instead of setSize()
Call setVisible(true)
in the end.
Good luck!
Upvotes: 2
Reputation: 109823
I have checked on internet but I Haven't found anything.
JFrame is visible before JComponents (frame.add(content);
) are added / created
move code line frame.setVisible(true);
(better everything about JFrame) to the end of constuctor
Upvotes: 6