Aspiring Antelope
Aspiring Antelope

Reputation: 95

Java null layout results in a blank screen

When I try to use setLayout(null), I get a plain gray screen and none of my components are present. Do I need to give every component in ColorPanel an x, y value?

import javax.swing.*;
import java.awt.*;

public class GUI{

    public static void main(String[] args){
        JFrame GUI = new JFrame();
        GUI.setLayout(null);
        GUI.setTitle("Betrai");
        GUI.setSize(500, 500);
        GUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ColorPanel panel = new ColorPanel(Color.white);
        Container pane = GUI.getContentPane();
        JButton continueButton = new JButton("TEST");
        continueButton.setBackground(Color.red);
        continueButton.setBounds(10, 10, 60, 40);
        pane.add(continueButton);
        GUI.setVisible(true);
        GUI.setBounds(0, 0, 500, 500);
        GUI.setResizable(false);
    }
}

Upvotes: 2

Views: 2512

Answers (2)

Steve McLeod
Steve McLeod

Reputation: 52448

When you use null for a layout manager, you are telling Swing that you want to do absolute positioning. The rules for absolute positioning is that you must set the bounds for each component you add to the Container before you add it.

Here is where you'll find Oracle's canonical example of using no layout manager. http://download.oracle.com/javase/tutorial/uiswing/layout/none.html

Note also, you should be wrapping everything as follows:

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        ... GUI creation stuff here ...
    }
});

Upvotes: 2

dacwe
dacwe

Reputation: 43504

I tried the code and I can see your button, just like you specified!

You need to add the ColorPanel to the layout and set the bounds (just like you did for the test button).

    panel.setBounds(50, 50, 100, 100);
    pane.add(panel);

But you should not use null layout. There is almost always another layout that can fullfill your needs!

Upvotes: 5

Related Questions