简体   繁体   English

如何在我的情况下使用CardLayout

[英]How to Use A CardLayout in My Situation

I have not been able to find a way to use a CardLayout that works. 我还没有找到使用CardLayout的方法。

I am creating a Pong game. 我正在创建一个Pong游戏。 I have a class that extends a JFrame and two classes that extend a JPanel. 我有一个扩展JFrame的类和两个扩展JPanel的类。 I am trying to make it so that when the method gets fired in the the first JPanel, it switches from the first JPanel to the second JPanel. 我正在尝试使其在第一个JPanel中触发该方法时,将其从第一个JPanel切换到第二个JPanel。

How would I do this, and please provide code. 我该怎么做,请提供代码。

What you do is use a CardLayout on the parent component that will hold your two JPanel s. 您要做的是在将容纳两个JPanel的父组件上使用CardLayout When you add the JPanel s to the parent component, you'll need to provide a String for each one, which will be used later to switch between the cards. JPanel添加到父组件时,需要为每个组件提供一个String ,稍后将在各卡之间使用该String进行切换。

CardLayout cardLayout = new CardLayout();
JPanel parentComponent = new JPanel(cardLayout);
parentComponent.add( jPanel1, "Panel 1" );
parentComponent.add( jPanel2, "Panel 2" );

Then when you want to switch the cards, you need to call a method on the CardLayout layout manager, so you'll need to get it from the parent component and cast it, or just save a reference to it when you create your parent component. 然后,当您要切换卡片时,您需要在CardLayout布局管理器上调用一个方法,因此您需要从父组件中获取方法并进行转换,或者在创建父组件时仅保存对其的引用。 Now to switch the cards: 现在切换卡:

cardLayout.show( parentComponent, "Panel 1" ); // Shows panel 1
cardLayout.show( parentComponent, "Panel 2" ); // Shows panel 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM