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

查看:36
本文介绍了在 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天全站免登陆