0

我正在尝试存储用户输入文本的输出,这只是它的模板,但我似乎无法找到正确访问 JTextArea 的方法,我发现的所有示例都以不同的方式进行然后我正在尝试完成它,是否可以这样做?

import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.*;

public class HelloWorldSwing {
private JFrame mainFrame;
private JLabel headerLabel;
private JLabel statusLabel;
private JPanel controlPanel;


public HelloWorldSwing(){
    prepareGUI();
}
public static void main(String[] args){
    HelloWorldSwing swingControlDemo = new HelloWorldSwing();
    swingControlDemo.showEventDemo();
}
private void prepareGUI(){
    mainFrame = new JFrame("Java Swing Demo");
    mainFrame.setSize(400,400);
    mainFrame.setLayout(new GridLayout(3,1));

    headerLabel = new JLabel("",JLabel.CENTER);
    statusLabel = new JLabel("",JLabel.CENTER);
    statusLabel.setSize(350,100);

    mainFrame.addWindowFocusListener(new WindowAdapter() {
        public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
        }
    });
    controlPanel = new JPanel();
    controlPanel.setLayout(new FlowLayout());

    mainFrame.add(headerLabel);
    mainFrame.add(controlPanel);
    mainFrame.add(statusLabel);
    mainFrame.setVisible(true);
}
private void showEventDemo(){
    headerLabel.setText("Control in action: Button");


    JButton submitButton = new JButton("Submit");
    JTextField userTextField = new JTextField("all",26);

    submitButton.setActionCommand("Submit");

    submitButton.addActionListener(new ButtonClickListener());

    controlPanel.add(userTextField);
    controlPanel.add(submitButton);

    mainFrame.setVisible(true);

}

private class ButtonClickListener implements ActionListener {
    @Override
    public void actionPerformed(ActionEvent e){
        JTextField textField = (JTextField) e.getSource();
        String text = textField.getText();
        statusLabel.setText(text);

    }
}

}

4

1 回答 1

2

首先,将showEventDemo()代码移动到设置 GUI 中(因为它仍在设置 GUI)。

您有一个名为的类ButtonClickListener,它正在侦听一个JButton对象,接收ActionEvents来自JTextField. 这不是一个明智的方法,因为ActionEvent它只会有一个JButton你添加它作为监听器的源。

相反,您需要重写您的侦听器。你可以为它创建一个构造函数,传入JTextField.

private class StatusUpdateListener implements ActionListener {
    private JTextField input;
    private JLabel status;

    public SubmitButtonListener(JTextField source, JLabel dest) {
       input = source;
       status = dest;
    }

    public void actionPerformed(ActionEvent e){
        String text = input.getText();
        status.setText(text);
    }
}

然后它会在一些地方使用

submitButton.addActionListener(new StatusUpdateListener(userTextField, statusLabel));
于 2017-07-11T16:20:57.483 回答