在包含在JFrame中的JFrame中看不到JPanel

时间:2019-06-10 11:19:20

标签: java swing jpanel

编译后,在JPanel中找不到我的JFrame,框架设置为BorderLayout,面板设置为CENTER,但是运行时该面板不会出现。我的代码中缺少什么吗?

    JFrame mainWindow = new JFrame("Francisco's System");
    mainWindow.setBounds(10,10,1024,700);

    borderEncode = BorderFactory.createTitledBorder("Encode Module");
    borderBackup = BorderFactory.createTitledBorder("Backup Module");
    borderRestore = BorderFactory.createTitledBorder("Restore Module");
    lbl_testpanel1 = new JLabel("This is the Encode Panel");
    lbl_testpanel2 = new JLabel("This is the Backup Panel");
    lbl_testpanel3 = new JLabel("This is the Restore Panel");
    mb = new JMenuBar();
    menu1 = new JMenu("Functions");
    menu2 = new JMenu("Help");
    menu1_encode = new JMenuItem("Encode");
    menu1_backup = new JMenuItem("Backup");
    menu1_restore = new JMenuItem("Restore");
    panelEncode = new JPanel();
    panelBackup = new JPanel();
    panelRestore = new JPanel();
    panelMain = new JPanel();

    menu1_encode.addActionListener(control);
    menu1_backup.addActionListener(control);
    menu1_restore.addActionListener(control);

    menu1.add(menu1_encode);
    menu1.add(menu1_backup);
    menu1.add(menu1_restore);
    mb.add(menu1);
    mb.add(menu2);

    mainWindow.setLayout(new BorderLayout());

    panelEncode.setLayout(new FlowLayout());
    panelEncode.add(lbl_testpanel1);
    panelEncode.setBorder(borderEncode);

    panelBackup.setLayout(new FlowLayout());
    panelBackup.add(lbl_testpanel2);
    panelBackup.setBorder(borderBackup);

    panelRestore.setLayout(new FlowLayout());
    panelRestore.add(lbl_testpanel3);
    panelRestore.setBorder(borderRestore);

    panelMain.setLayout(new FlowLayout());
    panelMain.setBorder(BorderFactory.createLineBorder(Color.blue));
    panelMain.setBackground(Color.red);

    mainWindow.add(panelMain, BorderLayout.CENTER);
    mainWindow.add(mb);
    mainWindow.setJMenuBar(mb);

    mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);`enter code here`
    mainWindow.setVisible(true);
}

我希望面板出现并跨越框架的宽度和高度,但不会显示。

1 个答案:

答案 0 :(得分:1)

  

我不知道那里出了什么问题,但是可以解决

mainWindow.add(panelMain, BorderLayout.CENTER);
mainWindow.add(mb);

以上两个语句是同一件事。如果未指定约束,则默认情况下BorderLayout将使用“ CENTER”。

只能将单个组件添加到BorderLayout中的任何给定区域。

因此添加菜单栏将替换现有组件,即您的panelMain。