首页 > 解决方案 > 将用户输入(来自 TextField)传递给另一个类?

问题描述

我有以下问题:我的游戏中有 2 个类 - CONFIGUREGAME (CG) 和 ROULETTETABLE (RT) - 用户可以在类 CG 中指定有关游戏的详细信息,例如他的姓名或金钱。在 RT 类中,我希望来自 CG 类的 JTextField 的输入显示在 RT 类的按钮上。

这是我的代码(我简化了很多):

public class CONFIGUREGAME extends JFrame implements ActionListener
{
    Jframe frame = new JFrame("...");
    public JTextField playername1 = new JTextField();
    public JButton startgame = new JButton();

    public CONFIGUREGAME()
    {
        startgame.addActionListener(this);
    }

    public static void main(String (String[] args) 
    {
       new CONFIGUREGAME();
    }

    public void actionPerformed(ActionEvent aEvt) 
    {
        if(aEvt.getSource()==startgame)
        {
            frame.dispose();
            new ROULETTETABLE();
        }
    }

现在第 2 类:

import ...;

public class ROULETTETABLE extends CONFIGUREGAME implements ActionListener
{
     public player1 = new JButton();

     public ROULETTETABLE()
     {
         String Strplayername1 = playername1.getText();
         player1.setText(Strplayername1);
     }

     public static void main(String (String[] args) 
     {
         new ROULETTETABLE();
     }
}

我尝试了各种应该有帮助的方法,但它们没有。我的 UI 工作得很好,所以如果其中有错误,那是因为我在简化它时犯了一个错误。我感谢任何帮助!

标签: javaswing

解决方案


你需要这样的东西。

public class CONFIGUREGAME extends JFrame implements ActionListener
{
    Jframe frame = new JFrame("...");
    public JTextField playername1 = new JTextField();
    public JButton startgame = new JButton();

    public CONFIGUREGAME()
    {
        startgame.addActionListener(this);
    }

    public static void main(String (String[] args) 
    {
       new CONFIGUREGAME();
    }

    public void actionPerformed(ActionEvent aEvt) 
    {
        if(aEvt.getSource()==startgame)
        {
            frame.dispose();
            new ROULETTETABLE(playername1.getText());
        }
    }
}

public class ROULETTETABLE extends CONFIGUREGAME implements ActionListener
{
     public JButton player1 = new JButton();

     public ROULETTETABLE(String playerName)
     {
         player1.setText(playerName);
     }

     public static void main(String (String[] args) 
     {
         new ROULETTETABLE();
     }
}

PS请学习Java方法和类符号。CapitalizedClassName, firstWordLowercaseMethodName, firstWordLowercaseVariableName,UPPER_CASE_CONSTANT_NAME


推荐阅读