2016-11-13 15 views
-1

この時点で、Carクラス、CarGUIクラス、およびactionlistenerという3つのクラスがあります。私は、Carクラスの新しいインスタンスを作成し、それをactionlistenerで参照させたいと思います。私がメインメソッドの外でそれを宣言し、グローバル化すると、すべて正常に動作します。問題は、メインの方法で新しい車を宣言しなければならないことです。私はいくつかの他のものと同様に動作しなかったメインメソッドでアクションリスナーを入れ子にしてみました。これに取り組む方法が不明です。どんな助けもありがとうございます。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") 
     } 
    } 
} 

答えて

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; 
    .... 

注 - コンストラクタ偶然にまたはセッターメソッドを経由して。

関連する問題