Java null layout results in a blank screen

2019-02-27 13:30发布

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

2条回答
forever°为你锁心
2楼-- · 2019-02-27 14:01

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!

查看更多
不美不萌又怎样
3楼-- · 2019-02-27 14:02

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 ...
    }
});
查看更多
登录 后发表回答