我正在尝试使用NetBeans IDE 8.2从头开始编写GUI。我决定将我的RPG游戏基于Card Layout。因此,布局从卡“信息窗格”开始,我可以在第一个开关上更改面板,但是我不太确定如何让它们交换回来。我让程序在控制台上打印了一个字符串,以便确保卡切换正确。
package guigamefromscratch;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUIGameFromScratch implements ItemListener{
static String[] Classes = {
"Barbarian",
"Fighter",
"Rogue",
"Wizard"
};
static String[] Races = {
"Dwarf",
"Gnome",
"Half-Orc",
"Human"
};
static String[] Gender = {
"Male",
"Female"
};
static String cls;
static String rcs;
static String gen;
static String gameName = "RPG Text";
static Component frame = null;
static Component icon = null;
static JPanel cards;
static GUIGameFromScratch work = new GUIGameFromScratch();
static JPanel card1;
public static void main(String[] args) {
Classes(Classes);
Races(Races);
Gender(Gender);
work.Run();
}
public static void Classes(String[] Classes){
cls = (String)JOptionPane.showInputDialog(frame,
"Choose a Class:",
gameName,
JOptionPane.PLAIN_MESSAGE, (Icon) icon,
Classes,
Classes[0]
);
}
public static void Races(String[] Races){
rcs = (String)JOptionPane.showInputDialog(frame,
"Choose a Race:",
gameName,
JOptionPane.PLAIN_MESSAGE, (Icon) icon,
Races,
Races[0]
);
}
public static void Gender(String[] Gender){
gen = (String)JOptionPane.showInputDialog(frame,
"Choose a Gender:",
gameName,
JOptionPane.PLAIN_MESSAGE, (Icon) icon,
Gender,
Gender[0]
);
}
public void Run(){
JFrame display = new JFrame();
display.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
display.pack();
display.setSize(300,250);
display.setTitle(gameName);
display.setVisible(true);
display.setResizable(false);
JPanel comboBoxPane = new JPanel();
String[] comboBoxItems = {"Info Pane", "Game Pane"};
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
card1 = new JPanel();
card1.add(new JLabel("Class: " + cls));
card1.add(new JLabel("Race: " + rcs));
card1.add(new JLabel("Gender: " + gen));
cards = new JPanel(new CardLayout());
cards.add(card1, comboBoxItems[0]);
display.add(comboBoxPane, BorderLayout.PAGE_START);
display.add(cards, BorderLayout.CENTER);
comboBoxPane.setVisible(true);
cards.setVisible(true);
card1.setVisible(true);
}
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED){
cards.setVisible(false);
card1.setVisible(false);
System.out.println("This is America");
cards.revalidate();
card1.revalidate();
cards.repaint();
card1.repaint();
}
else {
cards.setVisible(true);
card1.setVisible(true);
}
}
}
如果有人有任何帮助,我将不胜感激。