-1

在这一点上,我有三个与我相关的类: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")
        }
    }
}
4

1 回答 1

1

将 Car 传递到 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 无关,而是将信息从静态世界传递到实例的基本方法——通过构造函数参数或设置方法。

于 2016-11-13T16:20:34.180 回答