【问题标题】:How to access variable in main method from actionlistener如何从 actionlistener 访问 main 方法中的变量
【发布时间】:2016-11-14 00:34:19
【问题描述】:

此时我有三个与我相关的类:Car 类、CarGUI 类和 actionlistener。我想创建一个 Car 类的新实例并在 actionlistener 中引用它。当我在 main 方法之外声明它,使其成为全局时,一切正常。问题是我必须在 main 方法中声明新车。我尝试将 actionlistener 嵌套在不起作用的 main 方法中,以及其他一些事情。不知道如何解决这个问题。任何帮助表示赞赏。

//Create CarGUI that is child of JFrame and can interaction with interface of ActionListener and AdjustmentListener
public class CarGUI extends JFrame implements ActionListener, AdjustmentListener
{
    //  //declares variable and instantiates it as Car object to connect CarGUI with Car class
    //  Car c = new Car("car");
    public static void main(String[] args)
    {
        //declares variable and instantiates it as Car object to connect CarGUI with Car class
        Car c = new Car("car");

        //Declares frame of type CarGUI(JFrame)
        //and instantiates it as a new CarGUI(JFrame)
        CarGUI frame = new CarGUI();
    }
    public void actionPerformed( ActionEvent e )
    {
        //creates variable that will capture a string when an event occures
        String cmd = e.getActionCommand();
        //if statement triggered when JButton is clicked
        if ( cmd.equals("Create"))
        {
            //grabs strings from JTextFields and JScollBall and sets them to their
            //corresponding variables using the methods in the Car class
            c.setName(NameF.getText());
            c.setType(TypeF.getText());
            c.setYear(YearF.getText());
            //inverts the values on SBar and sets it to the variable speed
            //when getValue grabs the int it is inverted by subtraction 300
            //and mutplying by -1. the int is then converted to string
            c.setSpeed(Integer.toString(((SBar.getValue()-300)*-1)));

            //resets JTextFields JScrollBar and JLabel
            NameF.setText("");
            TypeF.setText("");
            YearF.setText("");
            SBar.setValue(0);
            SBarL.setText("Speed")
        }
    }
}

【问题讨论】:

    标签: java nested actionlistener main-method


    【解决方案1】:

    将汽车传递到 GUI:

    Car c = new Car("car");
    
    CarGUI frame = new CarGUI(c); // pass it in
    

    然后使用参数设置类的实例字段。

    例如,

    private Car car;
    
    public CarGUI(Car car) {
        this.car = car;
        .... 
    

    请注意,这与 Swing 无关,而是将信息从静态世界传递到实例的基本方式——通过构造函数参数或设置方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      • 1970-01-01
      • 2020-07-06
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      相关资源
      最近更新 更多