-1

I have three classes that are concerning me at this point: a Car class, CarGUI class, and actionlistener. I want to create a new instance of a Car class and have it referenced in the actionlistener. When I declare it outside of the main method, making it global, everything works fine. The problem is I have to declare the new Car in the main method. I have tried nesting the actionlistener in the main method which did not work, as well as a few other things. Not sure how to tackle this one. Any help is appreciated.

//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")
        }
    }
}
Pham Trung
  • 11,204
  • 2
  • 24
  • 43
R Mason
  • 1
  • 2

1 Answers1

1

Pass the Car into the GUI:

Car c = new Car("car");

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

And then use the parameter to set an instance field of the class.

e.g.,

private Car car;

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

Note that this has nothing to do with Swing, but is a basic way to pass information from the static world into an instance -- via constructor paramters or setter methods.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373