这个 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);
}
}
当我在文本框中输入我的名字,然后单击提交时,它只是说'欢迎,空'。actionlistener 似乎没有被触发。