JLabel doesn't show up

2019-02-20 18:17发布

问题:

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);
    }       
}

回答1:

Set a layout for your panel. Per example :

loginpanel.setLayout(new BorderLayout());

You can learn more about layouts here.

Here's what I get :



回答2:

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



回答3:

  1. Use layouts. FlowLayout should be fine in this case. Do not call setBounds() and do not set layout as a null.

  2. Add label and button on JPanel

  3. Then add JPanel on JFrame

  4. Call pack() instead of setSize()

  5. Call setVisible(true) in the end.

Good luck!



回答4:

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);
    }