【发布时间】:2018-12-01 03:33:57
【问题描述】:
我有一个快速的问题,我肯定有一个快速的答案,但我尽可能地尝试我就是无法弄清楚。
所以我正在编写一个需要在不同时间显示不同屏幕的游戏代码。我不知道怎么做,所以我决定用一个小程序来练习。在我的小程序中,我想要三个屏幕:屏幕 1 有一个打开屏幕 2 的按钮,屏幕 2 有一个打开屏幕 3 和屏幕 3 的按钮以及一个打开屏幕 1 的按钮!:
通过一些研究,我发现我可以使用 CardLayout 来做到这一点。在过去的一个小时里,我在互联网上来回走动,这就是我能想到的:
public class DifferentScreensTester extends JFrame implements ActionListener{
CardLayout cl = new CardLayout();
Container contentpane = getContentPane();
JPanel cards = new JPanel();
JPanel screen1 = new JPanel();
JPanel screen2 = new JPanel();
JPanel screen3 = new JPanel();
JButton screen1b = new JButton("Go to screen 1");
JButton screen2b = new JButton("Go to screen 2");
JButton screen3b = new JButton("Go to screen 3");
//constrcutor
public DifferentScreensTester() {
super();
contentpane.setLayout (cl);
//add buttons to respective screens
screen1.add(screen2b);
screen2.add(screen3b);
screen3.add(screen1b);
//add screens to content pane
contentpane.add(screen1, "Screen 1");
contentpane.add("Screen 1", screen1);
contentpane.add("Screen 2", screen2);
contentpane.add("Screen 3", screen3);
//action listeners
screen1b.addActionListener(this);
screen2b.addActionListener(this);
screen3b.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent event) {
if (event.getSource() == screen1b) {
cl.show(screen1, "Screen 1");
}
if (event.getSource() == screen2b) {
cl.show(screen2, "Screen 2");
}
if (event.getSource() == screen3b) {
cl.show(screen3, "Screen 3");
}
}
public static void main(String [] args) {
//Scanner sc = new Scanner(System.in);
DifferentScreensTester clmain = new DifferentScreensTester();
clmain.setSize(400, 400);
clmain.setVisible(true);
clmain .setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
第一次运行顺利进行。屏幕 1 使用按钮 2 自动打开。 Here's a picture of what I see. 然而,当我点击按钮的那一刻,我收到了一条长得可怕的错误消息。这与为 CardLayout 调用错误的父级有关。
但是在过去的半小时里我一直在修改我的代码并且无法修复它!我发现的示例代码对于我这个低级初学者来说太复杂了,甚至无法开始理解。
如果有人,任何人,可以请告诉我正在发生的事情以及如何解决它,我们将不胜感激。如果您需要任何额外的信息,我会提供!谢谢!
【问题讨论】:
-
I get a terrifyingly-lengthy error message. It's something about calling the wrong parent for CardLayout- 您收到的实际错误消息将与问题一起发布。
标签: java swing jframe layout-manager cardlayout