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.