在这一点上,我有三个与我相关的类:Car 类、CarGUI 类和 actionlistener。我想创建一个 Car 类的新实例并在 actionlistener 中引用它。当我在 main 方法之外声明它,使其成为全局时,一切正常。问题是我必须在 main 方法中声明新车。我尝试将 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")
}
}
}