-1

I have the following fragment of code, where a JLabel is not displayed unless I move the JFrame out of the screen and back in again. I tried to change the layout from null to BorderLayout or FloatLayout without much luck so far. Any ideas?

public class StartPage extends Main{

// Global variables
private JPasswordField passField = new JPasswordField();
private String infoLabel =  "<html>Bla, bla some text</html>";

// CONSTRUCTOR
public StartPage() {
    frame.setSize(1400, 1000);
    frame.setLocationRelativeTo(null); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.setResizable(false);
    startPage.setBounds(0, 0, 1400, 1000);  
    startPage.setLayout(null);
    frame.getContentPane().add(startPage);

    // TITLE LABEL
    JLabel lblTitle = new JLabel("My Title");
    lblTitle.setForeground(Color.RED);
    lblTitle.setHorizontalAlignment(SwingConstants.CENTER);
    lblTitle.setFont(new Font("Arial Black", Font.BOLD, 30));
    lblTitle.setBounds(190, 150, 1000, 85);
    startPage.add(lblTitle);

    // TEXT LABEL       
    JLabel areaText = new JLabel(infoLabel, SwingConstants.CENTER); 
    areaText.setVerticalAlignment(SwingConstants.CENTER);
    areaText.setBounds(315, 220, 750, 300);
    areaText.setFont(new Font("Arial Black", Font.PLAIN, 15));  
    areaText.setVisible(true);
    startPage.add(areaText);
Vlad Balanescu
  • 664
  • 5
  • 27

2 Answers2

2
  1. This line:

    frame.setVisible(true);
    

    Should be the last one in your program, it should be called after you've added all your components to it.

  2. Another thing that is wrong with your code is this:

    startPage.setLayout(null);
    

    Calling setLayout null will break your GUI, it might seem easy for complex GUIs but here's a good example of what happens when you run it in another machine with different resolution, OS, PLAF, etc. Use one or a combination of layout managers.

Frakcool
  • 10,915
  • 9
  • 50
  • 89
0

You have two solutions, call frame.invalidate() after finishing layout or call setVisible(true) after finishing layout;

Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167