一个JFrame中有两个面板? [英] Two Panels in one JFrame?

查看:224
本文介绍了一个JFrame中有两个面板?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个面板,希望它们显示在我的JFrame中,但是当我这样尝试时,我只能看到第二个面板.有人可以帮帮我吗? :(

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

推荐答案

您已经将两个面板都添加到了JFrameBorderLayout.CENTER中-只有一个可以占据该位置.这将是最后添加的,在这种情况下为panel2.

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.

要使面板均匀占据空间,可以使用GridLayout:

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

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

此外:更好地使用键绑定在Swing中注册组件的关键事件时.

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

这篇关于一个JFrame中有两个面板?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆