此时我有三个关于我的类:Car类,CarGUI类和actionlistener。我想创建一个Car类的新实例,并在actionlistener中引用它。当我在主方法之外声明它,使其全局化时,一切正常。问题是我必须在main方法中声明新的Car。我已经尝试在不起作用的main方法中嵌套actionlistener,以及其他一些东西。不知道如何解决这个问题。任何帮助表示赞赏。
//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")
}
}
}
答案 0 :(得分: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无关,但它是将信息从静态世界传递到实例的基本方法 - 通过构造函数参数或setter方法。