Java - 从不同的 class 调用变量,当按下 JButton 时,其值取自 JTextField

Java - Calling a variable from a different class which's value is taken from a JTextField when a JButton has been pressed

我正在尝试创建一个选择自己命运的冒险游戏。我创建了如下所示的图形用户界面:

显示的JTextField 将成为按下按钮时输入的输入框。我正在尝试编写代码,以便在按下按钮时将其内容保存到一个名为 UserInput 的变量中,然后我可以在主 class 中调用它以使用其内容。

我的主要 class 目前只是:

public class Main 
{
    public static void main(String[] args)
    {
        int i = 0;
        int t = 0;
        int st = 0;
        int h = 0;

        Texts textObject = new Texts();
        textObject.TextList();

        Commands commandObject = new Commands();
        commandObject.commands();

        GUImain guiObject = new GUImain();
        guiObject.displayGUI();

        String User_Input = guiObject.();       
    }
}

最后一行是我想从 GUImain 调用字符串的地方 class

这是我的 GUImain class 我已经尝试删除与这个问题无关的代码:

import's (lots of them);

public class GUImain 
{
    private JFrame frame;
    private JTextField textField;
    private ImageIcon image1;

    public void displayGUI() 
    {
        this.frame.setVisible(true);
    }

    //Launch the application.
    public static void main(String[] args)
    {
        GUImain window = new GUImain();
    }


    //Create the application.
    public GUImain() 
    {
        frame = new JFrame();
        frame.setBounds(100, 100, 611, 471);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

...

创建 JButton 并尝试将其 link 添加到文本字段并将其内容保存到变量 UserInput,我想从主 class:

        JButton btnEnter = new JButton("Enter"); //enter button
        btnOptions.addActionListener(new ActionListener() 
        {
            public String UserInput = "null";
            public void actionPerformed(ActionEvent e) 
            {
               UserInput = textField.getText();
            }
            public String getUserInput()
            {
               return UserInput;
            }
        });
        btnEnter.setBounds(518, 404, 85, 39);
        frame.getContentPane().add(btnEnter);

...

创建文本字段:

        textField = new JTextField(""); 
        textField.setBounds(5, 410, 508, 28);
        frame.getContentPane().add(textField);
        textField.setColumns(10);

我才刚刚开始学习java很抱歉问了这么一个基本的问题,但我已经坚持了很长一段时间了。

感谢您的宝贵时间和帮助。

托马斯

只需尝试使用 'GUImain' 作为 class 'Main' 中的内部 class 并声明一个变量

public String UserInput = "null";

在 'Main' class 中。此变量现在可以在您的 classes 中使用。