Search code examples
javaswinguser-interfacelayout-managernull-layout-manager

None of the elements in the JPanel display in JFrame


I have looked for similar questions for hours, but I got no idea about the problem. Hoping somebody could help me.

Here is the class SimulatedWindow apart from the imports:

public class SimulatedWindow extends JFrame {

    private JFrame defFrame = new JFrame();

    SimulatedWindow() {
        windowsInit();
    }

    private void windowsInit() {
        defFrame.setSize(new Dimension(600, 480));
        defFrame.setTitle("Radar Simulate System");
        defFrame.setLayout(null);
        defFrame.setLocation(100, 100);

        DefPanel defPanel = new DefPanel();
        // this.getContentPane().add(defPanel, BorderLayout.CENTER);
        this.add(new DefPanel());
        defFrame.add(defPanel);
        defFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        defFrame.setVisible(true);
    }

    class DefPanel extends JPanel {
        private LeftPanel myLeftPanel;
        private RightPanel myRightPanel;

        public DefPanel() {
            setLayout(null);
            myLeftPanel = new LeftPanel();
            myRightPanel = new RightPanel();

            add(new JButton("Hello World!"));
            add(myLeftPanel);
            add(myRightPanel);
            System.out.println("DefPAnel");
        }
    }


    class LeftPanel extends JPanel {
        private JButton avgSpeedButton = new JButton();
        private JButton trafficColumeButton = new JButton();
        private JLabel avgSpeedLabel = new JLabel();
        private JLabel trifficColumeLabel = new JLabel();
        private JLabel curTimeLabel = new JLabel();

        LeftPanel() {
            setLayout(null);
            this.setBounds(0, 0, this.getSize().width, this.getSize().height);

            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            curTimeLabel.setText(df.format(new Date()));
            add(curTimeLabel);

            add(avgSpeedButton);

            System.out.println("LeftPanel");
        }
    }
}

The main function follows:

public class SimulatedWindowTest {

    public static void main(String[] args) {
        SimulatedWindow simulatedWindow = new SimulatedWindow();
    }
}

None of the elements (JButton, JLabel) in the JPanel are displaying.


Solution

  • I believe this might be your problem: check it

    The main answer is:

    This is the problem with absolute positioning (or null layout). It requires you to set the sizes of all your components, otherwise they will stay are their default zero-size and won't appear. That's why it's always better to use a layout manager.