此 Java 应用程序应询问用户姓名,然后显示“欢迎,姓名”的文字。这是我的 Main.java
代码:
package NameGui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main
{
public static void main(String[] args)
{
JFrame form = new JFrame();
FlowLayout layout = new FlowLayout();
JPanel content = new JPanel();
JPanel top = new JPanel();
JLabel title = new JLabel();
JPanel innerForm = new JPanel();
JLabel inputLabel = new JLabel();
JTextField input = new JTextField();
JPanel bottom = new JPanel();
JButton submit = new JButton();
JFrame display = new JFrame();
JLabel nameDisplay = new JLabel();
Container formContainer = form.getContentPane();
Container displayContainer = display.getContentPane();
title.setText("Welcome! What is your name?");
inputLabel.setText("Name:");
submit.setText("Submit");
form.setTitle("Your name");
display.setTitle("Your name");
String name = null;
input.setText("Name Here");
submit.addActionListener(
new SwitchScreen(inputLabel, name, display, form));
top.add(title);
innerForm.add(inputLabel);
innerForm.add(input);
bottom.add(submit);
content.add(top);
content.add(innerForm);
content.add(bottom);
formContainer.add(content);
formContainer.setLayout(layout);
form.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
form.pack();
form.setVisible(true);
displayContainer.add(nameDisplay);
nameDisplay.setText("Your name: " + Aname);
display.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
display.pack();
display.setVisible(false);
}
}
下面是 Action Listener 的代码:
package NameGui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
class SwitchScreen implements ActionListener
{
JLabel inputLabel;
String name;
JFrame display;
JFrame form;
SwitchScreen(JLabel inputLabel, String name, JFrame display, JFrame form)
{
this.name = name;
this.inputLabel = inputLabel;
this.form = form;
this.display = display;
}
public void actionPerformed(ActionEvent ae)
{
name = inputLabel.getText();
form.setVisible(false);
display.setVisible(true);
}
}
当我在文本框中输入我的名字,然后单击提交时,它只显示“欢迎,null”。 Action 监听器似乎没有触发。
最佳答案
我认为您的代码中还有一些其他错误,因为这不会编译,但假设您解决了这些问题,您需要更新显示 "Welcome, "+ name
的标签。所以与其说 name = inputLabel.getText();
不如试试 outputField.setText("Welcome, "+ inputLabel.getText());
您需要将要在其中显示消息的任何对象传递给 SwitchScreen 对象,但这应该可行。
您遇到的另一个问题是您将 JLabel 而不是 JTextField 传递给监听器,因此即使它工作正常,显示也将是“欢迎,姓名:”
关于java - 从 Java Action 监听器返回一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17279364/