我正在尝试制作类似于文本冒险的东西,但是使用GUI而不是通过控制台。我希望能够多次将内容打印到Jlabel(它会不断切换到不同的字符串)。
我让它工作,但只有一次。我正在尝试使用printEnter(String toPrint)方法打印到打印到GUI。如您所见,printEnter方法被调用四次,但只有文本“one”被打印到GUI。但是,在Eclipse的控制台中,它会打印用户输入四次。如果我添加了第五个printEnter方法,它会打印五次,等等。因此,我知道它运行了四次,但它只更新了一次GUI。
我的目标是每当玩家按下回车键时,文本就会切换到预定义的字符串(如“打印”中的“一个”,“两个”,“三个”和“四个”)
有人可以让我知道如何在按下输入时简单地切换gui上的文字吗?我是事件处理程序的新手,所以我很有可能只是做了一些完全错误的事情。提前谢谢。
我的整个计划:
//Init scanner
static Scanner sc = new Scanner(System.in);
//Default text (appears when program first runs)
static JLabel textInputLabel = new JLabel("textLabel", SwingConstants.CENTER);
static JLabel textShown = new JLabel("", SwingConstants.CENTER);
static JLabel logoLabel = new JLabel("logoLabel", SwingConstants.CENTER);
//Name of window
static JFrame frame = new JFrame("Broken");
//JTextField edit and unedit, respectively
static JTextField editTextArea = new JTextField("Type here", SwingConstants.CENTER);
static String input;
private static void Window() {
//Text color and background color of print area, respectively
textInputLabel.setForeground(Color.black);
logoLabel.setForeground(Color.white);
frame.getContentPane().setBackground(Color.black);
textShown.setForeground(Color.yellow);
frame.getContentPane().add(textInputLabel, BorderLayout.AFTER_LINE_ENDS);
//Makes window and sets its properties
textInputLabel.setPreferredSize(new Dimension(800, 450));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
frame.requestFocus();
//Text input setup
frame.getContentPane().add(textShown, BorderLayout.AFTER_LINE_ENDS);
frame.add(editTextArea, BorderLayout.SOUTH);
frame.add(logoLabel, BorderLayout.NORTH);
//Background and text color of input area, respectively
editTextArea.setVisible(true);
editTextArea.setBackground(Color.black);
editTextArea.setForeground(Color.white);
editTextArea.setPreferredSize(new Dimension(0, 30));
}
public static void main(String[] args) {
Window();
doStuff();
}
public static void doStuff() {
logoLabel.setText(""
+ "<html> <center> "
+ "<font face=\"verdana\" size=\"20\"> <br> "
+ " Broken <br> "
+ " Program <br>"
+ " <font size=\"4\"> &ensp </font> ______________________ "
+ "</font>"
+ "</center> </html>");
printEnter("one");
printEnter("two");
printEnter("three");
printEnter("four");
}
public static void printEnter(String toPrint) {
editTextArea.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
input = editTextArea.getText();
textShown.setText("<html> <center> <font size=\"20\"> " + toPrint + " </font> </html>");
System.out.println("User inputted: \"" + input + "\"");
}
});
}