Java 如何从actionlistener访问main方法中的变量
目前我有三个类:Car类、CarGUI类和actionlistener。我想创建一个Car类的新实例,并在actionlistener中引用它。当我在主方法之外声明它时,使它成为全局的,一切都正常。问题是我必须用主要方法申报新车。我尝试过将actionlistener嵌套在main方法中,但没有成功,还有其他一些事情。我不知道怎么解决这个问题。感谢您的帮助Java 如何从actionlistener访问main方法中的变量,java,nested,actionlistener,main-method,Java,Nested,Actionlistener,Main Method,目前我有三个类:Car类、CarGUI类和actionlistener。我想创建一个Car类的新实例,并在actionlistener中引用它。当我在主方法之外声明它时,使它成为全局的,一切都正常。问题是我必须用主要方法申报新车。我尝试过将actionlistener嵌套在main方法中,但没有成功,还有其他一些事情。我不知道怎么解决这个问题。感谢您的帮助 //Create CarGUI that is child of JFrame and can interaction with inter
//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")
}
}
}
将汽车传递到GUI中:
Car c = new Car("car");
CarGUI frame = new CarGUI(c); // pass it in
然后使用该参数设置该类的实例字段
e、 g
请注意,这与Swing无关,而是通过构造函数参数或setter方法将信息从静态世界传递到实例的基本方法
private Car car;
public CarGUI(Car car) {
this.car = car;
....