Why don’t my labels show up in the swing?

Asked

Viewed 63 times

0

Can anyone help me? It’s a pretty rookie mistake because my Abels aren’t showing up in the swing?

import javax.swing.*;

public class first{

public static void main(String[] args){

    JFrame f = new JFrame();

    JLabel c = new JLabel("Seja bem-vindo!");
    f.add(c);
    JButton b = new JButton("CLICK");
    b.setBounds(130,100,100,40);

    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(b);
    f.setSize(400,500);
    f.setLayout(null);
    f.setVisible(true);  
  }
}

2 answers

0

It’s a more-or-less answer because I don’t have the upper hand in order to better explain what’s going on, but it should work if I do:

f.getContentPane().add(c);

You also need to remove the following line:

f.setLayout(null);

Always try to use layouts instead of setting them as null.

Study the code I modified below.

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class Main {

    public static void main(String[] args){

        SwingUtilities.invokeLater(

                new Runnable() {
                    @Override
                    public void run() {
                        JFrame f = new JFrame();
                        JLabel c = new JLabel("Seja bem-vindo!");
                        JPanel panel = new JPanel();
                        f.getContentPane().add(panel);
                        panel.add(c);
                        JButton b = new JButton("CLICK");
                        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        panel.add(b);
                        f.setSize(400,500);
                        f.setVisible(true);
                        //f.pack(); // Experimente com pack() para ver como fica
                    }
                });
    }

}

Note that:

  • I’m calling GUI code from within the EDT (Event-Dispatch Thread) via the invokeLater();

  • Because it’s a top-level container, Jframe has the content pane, which other containers like Jpanel don’t. I believe that it is not a good idea to touch the content pane for nothing, and only add a container to it (or more than one, maybe). This is done by working with the JPanel, defining the layout to be used or leaving the FlowLayout, which is the standard of this container.

0

When you work with null layout, you have to set the positioning of all objects. Your code is ok, you just forgot to position the label:

c.setBounds(50, 50, 100, 50);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.