繁体   English   中英

如何从另一个 class 调用方法以在我的 ActionListener class 中使用

[英]How do I call a method from another class to use in my ActionListener class

我正在尝试使用我的汽车 class 中的加速和制动方法,以便在按下特定按钮时在我的 CarView class 中使用它们。 当涉及到 ActionListeners 时,我的当前代码不断出现错误,我不确定从这里到 go 的位置。 这是我的代码。

import javax.swing.*; //Needed for Swing classes
import java.awt.event.*; // Needed for ActionListener Interface
public class CarView extends JFrame
{
    private JPanel panel; //To reference a panel
    private JLabel modelYearLable; //To reference a model year Label
    private JLabel makeLable; //To reference a make Label
    private JLabel speedLable; //To reference a speed Label
    private JTextField modelTextField; // To reference a model yeartext field
    private JTextField makeTextField; // To reference a make text field
    private JTextField speedTextField; // To reference a speed text field
    private JButton accelerateButton; // To reference an accelerate button
    private JButton brakeButton; // To reference a brake button
    private final int WINDOW_WIDTH = 310; // Window width
    private final int WINDOW_HEIGHT = 100; // Window heigh
    private final int carYear = Integer.parseInt(modelTextField.getText()); 
    private final String type = makeTextField.getText(); 
    Car vehicle = new Car(this.carYear, this.type); //Create an instance variable of the Car class!
    //Constructor 
    public CarView()
    {
        //Set the window titile.
        setTitle("Car referencer!");
        
        //Set the size of the window.
        setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
        
        // Specify what happens when the close button is clicked
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        //Build thhe panel and add it to the frame.
        buildPanel();
        
        //Add the panel to the frame's content pane.
        add(panel);
        
        //Display the window
        setVisible(true);
    }
        
    //buildPanel()
    //Responisibilities: Adds labels, text fields, and buttons to the panel
    private void buildPanel()
    {
       //Create labels to display instructions 
       modelYearLable = new JLabel("Enter the year of your model");
       makeLable = new JLabel("Enter the make of your car");
       speedLable = new JLabel("Enter the current speed of your car");
            
       //Create text fields as well
       modelTextField = new JTextField(5);
       makeTextField = new JTextField(5);
       speedTextField = new JTextField(5);
            
       //Create the buttons
       accelerateButton = new JButton("Accelerate");
       brakeButton = new JButton("Brake");
            
       //Add an action listener to the buttons
       accelerateButton.addActionListener(new AccelerateButtonListener());
       brakeButton.addActionListener(new BrakeButtonListener());
            
       //Create a JPanel object and let the panel field reference it. 
       panel = new JPanel();
            
       //Add the labels,text fields, and buttons to the panel
       panel.add(modelYearLable);
       panel.add(makeLable);
       panel.add(speedLable);
       panel.add(modelTextField);
       panel.add(makeTextField);
       panel.add(speedTextField);
       panel.add(accelerateButton);
       panel.add(brakeButton);
    }
        
    //AccelerateButtonListener is an action listener private inner class for the Accelerate Button.
    private class AccelerateButtonListener implements ActionListener
    {
        //The acitonPerformed method executes when the user clicks on the Accelerate Button
        public void actionPerformed(ActionEvent e)
        {
           vehicle.accelerate();//Using the instance variable we made of Car earlier we can call the accelerate method from Car class.
        }
           
    }
    
    
    //BrakeButtonListener is an action listener private inner class for the Brake Button.
    private class BrakeButtonListener implements ActionListener
    {
        //The actton Performed method executes when the user clicks on the Brake Button
        public void actionPerformed(ActionEvent e)
        {
           vehicle.brake();//Using the instance variable we made of Car earlier we can call the brake method from Car class.
        }
    }
    //The main method creates an instance of the CarView, which causes it to display its window
    public static void main(String[] args)
    {
        CarView cv = new CarView();
    }
    

这是汽车 Class

public class Car
{
    private int yearModel; //The yearModel is an int that holds the car's modcel year
    private String make; //The make references a String object that holds the make of the car.
    private double speed; //The speed field is a double that hold's thhe car's current speed.
    
    //Construtor that accepts the car's year model and make as arguments. These values should be assigned to the obkect's modelYear and make fields.
    //Also assign 0 to the speed
    public Car(int model, String type)
    {
        this.yearModel = model;
        this.make = type;
        speed = 0.0; //Set the speed to 0.
    }
    
    //Get and Set methods for modelYear, make and speed fields.
    
    //getModel
    //Responsibilities: gets the model of the car 
    public int getModel() 
    {
        return yearModel;
    }
    
    //getMake
    //Responsibilities: gets the make of the car 
    public String getMake() 
    {
        return make;
    }
    
    //getSpeed
    //Responsibilities: gets the speed of the car 
    public double getSpeedl() 
    {
        return speed;
    }
    
    //accelerate()
    //Responsibilities: Shouyld add 8 to the speed each time it is called 
    public void accelerate() 
    {
        speed = speed + 8; //Everytime this method is called, add 8 to the speed each time
    }
    
    //brake()
    //Responsibilities: Should  subtract 6 from the speed each time it is called.
    public void brake()
    {
        speed = speed - 6; //Everytime this method is called subtract 6 from speeed.
    }
}

错误

运行当前代码时出现 NullPointerException,但我不知道如何解决这个问题。 我只想在我的动作监听器中使用我的汽车 class 方法加速和制动,但我不知道如何。

感谢您提供任何帮助!

所以,当我运行你的代码时,我得到一个NullPointerException 仔细查看代码,我可以看到两个会导致此问题的问题...

public class CarView extends JFrame
{
    //...
    private JTextField modelTextField; // To reference a model yeartext field
    private JTextField makeTextField; // To reference a make text field
    //...
    private final int carYear = Integer.parseInt(modelTextField.getText()); 
    private final String type = makeTextField.getText(); 

在 class 的初始化阶段,您无法从modelTextFieldmakeTextField获取值,因为变量是null ,即使它们是,它们也会是空的,因为组件甚至还没有显示在屏幕上

相反,您需要在其他某个时间点获取值 - 请记住 GUI 是事件驱动的,而不是程序或线性的。

还有很多其他的东西,包括你在整个地方的布局; 没有验证; 当速度发生变化时,您不会向用户报告速度。

我可以 go 开启相当长的一段时间,但相反,我会给你一点推动

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.NumberFormat;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class CarView extends JFrame {

    private JPanel panel; //To reference a panel
    private JLabel modelYearLable; //To reference a model year Label
    private JLabel makeLable; //To reference a make Label
    private JLabel speedLable; //To reference a speed Label
    private JTextField modelTextField; // To reference a model yeartext field
    private JTextField makeTextField; // To reference a make text field
    private JTextField speedTextField; // To reference a speed text field
    private JButton accelerateButton; // To reference an accelerate button
    private JButton brakeButton; // To reference a brake button

    private JButton makeCarButton;

    //private final int carYear;
    //private final String type;

    private Car vehicle;

    //Constructor 
    public CarView() {
        //Set the window titile.
        setTitle("Car referencer!");

        //Set the size of the window.
        //setSize(WINDOW_WIDTH, WINDOW_HEIGHT);

        // Specify what happens when the close button is clicked
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Build thhe panel and add it to the frame.
        buildPanel();

        //Add the panel to the frame's content pane.
        add(panel);

        //Display the window
        pack();
        setVisible(true);
    }

    //buildPanel()
    //Responisibilities: Adds labels, text fields, and buttons to the panel
    private void buildPanel() {
        //Create labels to display instructions 
        modelYearLable = new JLabel("Enter the year of your model");
        makeLable = new JLabel("Enter the make of your car");
        speedLable = new JLabel("Enter the current speed of your car");

        //Create text fields as well
        modelTextField = new JTextField(5);
        makeTextField = new JTextField(5);
        speedTextField = new JTextField(5);

        //Create the buttons
        accelerateButton = new JButton("Accelerate");
        brakeButton = new JButton("Brake");

        //Add an action listener to the buttons
        accelerateButton.addActionListener(new AccelerateButtonListener());
        brakeButton.addActionListener(new BrakeButtonListener());

        // Don't want to use these until AFTER you've created a instance of Car
        accelerateButton.setEnabled(false);
        brakeButton.setEnabled(false);
        speedTextField.setEnabled(false);

        makeCarButton = new JButton("Make car");
        makeCarButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String make = makeTextField.getText();
                String model = modelTextField.getText();
                // Some funky validation
                if (make == null || make.isBlank() || model == null || model.isBlank()) {
                    // Add an error message
                    return;
                }
                int year = Integer.parseInt(model);

                vehicle = new Car(year, make);

                makeCarButton.setEnabled(false);
                accelerateButton.setEnabled(true);
                brakeButton.setEnabled(true);
                speedTextField.setEnabled(true);
            }
        });

        //Create a JPanel object and let the panel field reference it. 
        panel = new JPanel(new GridLayout(-1, 2));

        //Add the labels,text fields, and buttons to the panel
        panel.add(modelYearLable);
        panel.add(modelTextField);
        panel.add(makeLable);
        panel.add(makeTextField);

        panel.add(new JPanel());
        panel.add(makeCarButton);

        panel.add(speedLable);
        panel.add(speedTextField);

        panel.add(accelerateButton);
        panel.add(brakeButton);
    }

    //AccelerateButtonListener is an action listener private inner class for the Accelerate Button.
    private class AccelerateButtonListener implements ActionListener {

        //The acitonPerformed method executes when the user clicks on the Accelerate Button
        public void actionPerformed(ActionEvent e) {
            vehicle.accelerate();//Using the instance variable we made of Car earlier we can call the accelerate method from Car class.
            speedTextField.setText(NumberFormat.getInstance().format(vehicle.speed));
        }

    }

    //BrakeButtonListener is an action listener private inner class for the Brake Button.
    private class BrakeButtonListener implements ActionListener {

        //The actton Performed method executes when the user clicks on the Brake Button
        public void actionPerformed(ActionEvent e) {
            vehicle.brake();//Using the instance variable we made of Car earlier we can call the brake method from Car class.
            speedTextField.setText(NumberFormat.getInstance().format(vehicle.speed));
        }
    }

    //The main method creates an instance of the CarView, which causes it to display its window
    public static void main(String[] args) {
        CarView cv = new CarView();

    }

    public class Car {

        private int yearModel; //The yearModel is an int that holds the car's modcel year
        private String make; //The make references a String object that holds the make of the car.
        private double speed; //The speed field is a double that hold's thhe car's current speed.

        //Construtor that accepts the car's year model and make as arguments. These values should be assigned to the obkect's modelYear and make fields.
        //Also assign 0 to the speed
        public Car(int model, String type) {
            this.yearModel = model;
            this.make = type;
            speed = 0.0; //Set the speed to 0.
        }

        //Get and Set methods for modelYear, make and speed fields.
        //getModel
        //Responsibilities: gets the model of the car 
        public int getModel() {
            return yearModel;
        }

        //getMake
        //Responsibilities: gets the make of the car 
        public String getMake() {
            return make;
        }

        //getSpeed
        //Responsibilities: gets the speed of the car 
        public double getSpeedl() {
            return speed;
        }

        //accelerate()
        //Responsibilities: Shouyld add 8 to the speed each time it is called 
        public void accelerate() {
            speed = speed + 8; //Everytime this method is called, add 8 to the speed each time
        }

        //brake()
        //Responsibilities: Should  subtract 6 from the speed each time it is called.
        public void brake() {
            speed = speed - 6; //Everytime this method is called subtract 6 from speeed.
        }
    }
}

我建议看看:

花一些时间来更好地理解事件驱动的环境是如何工作的,这一点非常重要。 创建一些不做任何事情的按钮,将一些ActionListener附加到它们并使用System.out.println打印出正在发生的事情,这将帮助您了解它

include both class in same package so that you can create object of the first class in your second class. 希望你能理解 !

您可以从另一个 class 调用方法

文件:A.java

public class A {  
  private void message(){System.out.println("hello java"); }  
}  

文件:MethodCall.java

import java.lang.reflect.Method;  
public class MethodCall{  
public static void main(String[] args)throws Exception{  
  
    Class c = Class.forName("A");  
    Object o= c.newInstance();  
    Method m =c.getDeclaredMethod("message", null);  
    m.setAccessible(true);  
    m.invoke(o, null);  
}  
}  

Output:你好 java

从另一个 class 调用参数化私有方法的另一个示例让我们看一下从另一个 class 调用参数化私有方法的示例

文件:A.java

class A{  
private void cube(int n){System.out.println(n*n*n);}  
}  

文件:M.java

import java.lang.reflect.*;  
class M{  
public static void main(String args[])throws Exception{  
Class c=A.class;  
Object obj=c.newInstance();  
  
Method m=c.getDeclaredMethod("cube",new Class[]{int.class});  
m.setAccessible(true);  
m.invoke(obj,4);  
}}  

Output:64

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM