在JPanel之间切换 [英] Switching between JPanels

查看:261
本文介绍了在JPanel之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作游戏.游戏中有几个不同的屏幕,例如主菜单和实际游戏屏幕.这些都是独立的jpanel扩展.我已经将它们每个都添加到我的JFrame中,这是一个称为Game的类.在我的游戏课程中,我有以下方法

I'm trying to make a game. There's several different screens in the game such as a main menu, and the actual game screen. Each of these is a separate jpanel extension. I have added each of them to my JFrame which is a class called Game. In my game class I have the following methods

public void addPanel( JPanel p ) {
    panels.add( p ); // An array of all the different panels I need
    this.getContentPane().add( p );
}

public void switchToPanel( JPanel p ) {
    for ( JPanel somePanel : panels ) {
        somePanel.setVisible( false );
    }

    p.setVisible( true );
    repaint();
}

这一点是,我有许多不同的面板,当需要显示特定的面板时,例如菜单屏幕,我调用switchToPanel(myPanel).基本上只是隐藏每个面板,然后取消隐藏我需要查看的面板.唯一的问题是,当我切换到这些面板时,这些面板没有显示.唯一会出现的是我最后添加的面板.在Objective C中,我一直使用这种技术在视图之间进行切换,而我从​​来没有遇到任何问题.这种事情在Java中是不允许的吗?

The point of this is that I have many different panels and when I need to show a particular one, such as a menu screen, I call switchToPanel( myPanel ). Basically just hiding every panel and then unhiding the one that I need to see. Only problem is that these panels aren't showing up when I switch to them. The only one that will ever show up is the panel that I added last. In Objective C I use this technique for switching between views all the time and I've never had any problems. Is this kind of thing not allowed in java?

现在切换后我正在调用repaint(),但是它仍然无法工作

now I am calling repaint() after switching, but it's still not working

推荐答案

您可以做很多不同的事情来达到相同的效果.

You can do a number of different things to achieve the same effect.

我的第一个建议是使用 CardLayout ( 如何使用CardLayout ),因为这是它的初衷.

The first suggestion I'd make is use CardLayout (How to Use CardLayout) as this is what it was designed to do.

另一种方法是使用 JTabbedPane (如何使用选项卡式窗格)

这篇关于在JPanel之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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