2016-11-13 2 views
-1

J'ai trois classes qui me concernent à ce stade: une classe Car, une classe CarGUI et un actionlistener. Je veux créer une nouvelle instance d'une classe Car et la référencer dans l'actionlistener. Quand je le déclare en dehors de la méthode principale, le rendant global, tout fonctionne bien. Le problème est que je dois déclarer la nouvelle voiture dans la méthode principale. J'ai essayé d'imbriquer l'actionlistener dans la méthode principale qui n'a pas fonctionné, aussi bien que quelques autres choses. Je ne sais pas comment aborder celui-ci. Toute aide est appréciée.Comment accéder à la variable dans la méthode principale à partir de l'actionliste

//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") 
     } 
    } 
} 

Répondre

1

passer le voiture dans l'interface graphique:

Car c = new Car("car"); 

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

puis utilisez le paramètre pour définir un champ d'instance de la classe.

par exemple,

private Car car; 

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

Notez que cela n'a rien à voir avec Swing, mais est un moyen de transmettre des informations de base du monde statique dans une instance - via paramters ou des méthodes de réglage constructeur.