Two Panels in one JFrame?

旧巷老猫 提交于 2019-12-24 14:09:12

问题


i have two Panels and want them to be shown in my JFrame, but when i try it like this, i can only see the second one. Can someone please help me? :(

import javax.swing.JFrame;

public class MainWindow {

CardLayout layout;
JFrame frame;
Player panel1;
Block panel2;

public MainWindow() {
    frame = new JFrame("Rechteck");
    panel1 = new Player();
    panel2 = new Block();
    panel1.addKeyListener(new KeyListen(panel1));
    frame.add(panel1);
    frame.add(panel2);
    frame.setSize(500,500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}}

回答1:


You have added both your panels to the BorderLayout.CENTER of your JFrame—only one can occupy that location,. This will be the last one added, panel2 in this case.

To allow the panels occupy the space evenly, you could use GridLayout:

frame.setLayout(new GridLayout(2, 1));

Aside: Better to use Key Bindings when registering key events for components in Swing.




回答2:


Create a JPanel add that to the JFrame. Add panel1 and panel2 to the new panel. JFrame can only have one child, usually set by calling JFrame.setContentPane().



来源:https://stackoverflow.com/questions/14203714/two-panels-in-one-jframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!