我必须为学校制作一个游戏,我在通过单击 JButton 来切换 JPanel 时遇到了一些麻烦。我想使用 CardLayout,但我是 Java 新手,这很难。我的目标是将我的所有面板放在不同的类中,例如“面板 1”类、“面板 2”类等(而不是在我的主(JFrame)类中创建我的 JPanel,所以我的代码更容易阅读。是吗?可以将您的 CardLayout 容器放在包含我的 JFrame 的类中吗?还有,我在哪里放那个该死的 ActionPerformed?这是我的代码,希望你们能帮助我!
主(JFrame)类
package invers;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class InversMain extends JFrame implements ActionListener
{
public CardLayout cardlayout;
public Container contentPane = this.getContentPane();
public InversMain()
{
JFrame frame = new JFrame();
frame.setLayout(cardlayout);
frame.setSize(1366,768);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Invers");
frame.setResizable(true);
frame.setVisible(true);
contentPane.setPreferredSize(new Dimension(600, 400));
contentPane.add(new InversMainPaneel(), "Panel 1");
contentPane.add(new InstellingenPaneel(), "Panel 2");
settingsButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
cardlayout.show(contentPane, "Panel 1");
}
});}
public static void main ( String [] args)
{
new InversMain();
}
}
请注意,settingsButton 是我在 PANEL 1 类中的按钮。因为它不是在我的主类中创建的,所以它给出了一个错误。我想在我的主类中从 PANEL 1 类中引用我的 settingsButton。这可能吗?
面板 1,包含我的按钮的面板,这是我的主菜单页面
package invers;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JPanel;
public class InversMainPaneel extends JPanel
{
private JButton nieuwSpelKnop = new JButton("Nieuw spel");
private JButton laadSpelKnop = new JButton("Laad Spel");
private JButton settingsButton = new JButton("Settings");
private JButton handleidingKnop = new JButton("Handleiding");
public InversMainPaneel()
{
this.setLayout(null);
nieuwSpelKnop.setSize(300,40);
nieuwSpelKnop.setFont(new Font("Arial", Font.BOLD, 25));
nieuwSpelKnop.setLocation(520,250);
nieuwSpelKnop.setVisible(true);
laadSpelKnop.setSize(300,40);
laadSpelKnop.setFont(new Font("Arial", Font.BOLD, 25));
laadSpelKnop.setLocation(520,350);
laadSpelKnop.setVisible(true);
settingsButton.setSize(300,40);
settingsButton.setFont(new Font("Arial", Font.BOLD, 25));
settingsButton.setLocation(520,450);
settingsButton.setVisible(true);
handleidingKnop.setSize(300,40);
handleidingKnop.setFont(new Font("Arial", Font.BOLD, 25));
handleidingKnop.setLocation(520,550);
handleidingKnop.setVisible(true);
this.add(nieuwSpelKnop);
this.add(laadSpelKnop);
this.add(settingsButton);
this.add(handleidingKnop);
this.setBackground(new Color(178,143,79));
}
}
}
面板 2,用于测试卡片布局是否有效
package invers;
import java.awt.Color;
import javax.swing.JPanel;
public class InstellingenPaneel extends JPanel
{
public InstellingenPaneel()
{
this.setBackground(new Color(178,143,79));
}
}