None 的 JPanel 中的元素显示在 JFrame 中

None of the elements in the JPanel display in JFrame

我已经寻找了几个小时的类似问题,但我对这个问题一无所知。希望有人能帮助我。

这里是 class SimulatedWindow 除了进口:

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

主要功能如下:

public class SimulatedWindowTest {

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

None个元素(JButtonJLabel)正在显示。

我相信这可能是您的问题:check it

主要答案是:

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.