使用私有 class 访问 JTextField

Accessing JTextField using a private class

我正在尝试存储用户输入文本的输出,这只是它的一个模板,但我似乎无法找到正确访问 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);

    }
}

}

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

您有一个名为 ButtonClickListener 的 class,它正在侦听 JButton 对象,接收来自 JTextFieldActionEvents。这不是一个明智的方法,因为 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));