我已经为我想要制作的基于文本的游戏创建了一个GUI。 我将GUI实现到已经运行的游戏机制中,但是当我加载它时,GUI不会出现。 页面上没有错误,eclipse将运行游戏的其余部分,而不是与GUI相关的任何内容。 (我已经为GUI添加了整个代码,但只包含游戏的一部分来缩短代码。) 代码如下:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
DemoGUI inst = new DemoGUI();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public DemoGUI() {
super();
initGUI();
}
public void initGUI() {
try {
FlowLayout thisLayout = new FlowLayout();
getContentPane().setLayout(thisLayout);
setDefaultCloseOperation(EXIT_ON_CLOSE);
jLabel1 = new JTextArea();
getContentPane().add(jLabel1);
jLabel1.setPreferredSize(new Dimension(320, 250));
jLabel1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jButton1 = new JButton();
getContentPane().add(jButton1);
jButton1.setPreferredSize(new Dimension(100, 50));
jButton1.setText("Map");
jButton1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
}
});
jButton2 = new JButton();
getContentPane().add(jButton2);
jButton2.setPreferredSize(new Dimension(100, 50));
jButton2.setText("Inventory");
jButton2.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
jText1.setText("Health: " + EAID.CharHealth);
jText1.setText("Number of potions: " + EAID.CharPotionLevel);
jText1.setText("Weapon: ");
jText1.setText("Armor: ");
}
});
jButton4 = new JButton();
getContentPane().add(jButton4);
jButton4.setPreferredSize(new Dimension(100, 50));
jButton4.setText("Return");
jButton4.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
jLabel1.setText("");
jText1.setText("");
}
});
jText1 = new JTextField();
getContentPane().add(jText1);
jText1.setPreferredSize(new Dimension(320, 100));
jText1.setBorder(BorderFactory.createLineBorder(Color.BLACK));
jButton3 = new JButton();
getContentPane().add(jButton3);
jButton3.setPreferredSize(new Dimension(100, 40));
jButton3.setText("Submit");
jButton3.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
jText1.setText("");
jLabel1.setText("THIS IS A TEST");
}
});
//Scanner
Scanner scan = new Scanner(System.in);
//Introduction
jLabel1.setText("Hello adventurer. This is a tale of old, taking place in the long lost kingdom of Asteroth.\r\n" +
"This is a land tormented by the tyranical rule of the Lich King Astotle.\r\n" +
"For centuries he has tormented the citizens, leading to widespread famine and terror throughout the land.\r\n" +
"The story you are about to go on follows the tale of a young hero, on there quest to bring peace to the land.\r\n" +
"But tell me adventurer..");
在关闭类和主字符串之前,它会添加到文档的最底部:
pack();
this.setSize(350, 500);
} catch (Exception e) {
e.printStackTrace();
}
答案 0 :(得分:1)
删除扫描仪允许GUI加载
因此,您无法在事件发送线程(EDT)上执行扫描程序。
因此,您需要为Thread
创建另一个Scanner
。一种方法是使用SwingWorkder
。
阅读Concurrency上Swing教程中的部分,了解有关EDT
的更多信息以及使用SwingWorker
的示例。