在另一个 class 中调用方法

Calling method in another class

这看起来像是第 10000 个相似主题之一,但我就是找不到相似主题。我已经在这上面花了足够多的时间来问你们了。 我想要实现的是在另一个 class 中使用方法 "calculateM()"。它们都需要导入等。方法 returns 字符串编号。我不知道怎么称呼它。

package tripCostCalculator;

import java.text.DecimalFormat;
import javax.swing.JOptionPane;

public class calculation extends tripCostCalculatorUI {

    float miles, averageFuel, fuelPrice, tripCost, result;
    String number = "";

    public String calculateM() {

        if(jTextField1.getText().isEmpty() || 
           jTextField2.getText().isEmpty() || 
           jTextField3.getText().isEmpty()) {
               JOptionPane.showMessageDialog(jtp ,"Fill in all the boxes.");
        } else {
            miles = Float.parseFloat(jTextField1.getText());
            averageFuel = Float.parseFloat(jTextField2.getText());
            fuelPrice = Float.parseFloat(jTextField3.getText());

            tripCost = averageFuel * fuelPrice;
            result = (miles / 60) * tripCost;

            DecimalFormat decimalFormat = new DecimalFormat("##.##");
            float twoDigitsResult = Float.valueOf(decimalFormat.format(result));


            number = String.valueOf(twoDigitsResult);
            //jTextField4.setText("£" + String.valueOf(twoDigitsResult));
        }
        return number;
    }

??

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {       
        calculateM();
}

嗯,如果您从 calculation class 调用此方法,则该调用将有效 你需要做的是像这样实例化一个对象:

tripCostCalculatorUI obj = new calculation();
obj.calculateM();
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {       

    Calculator calculator= new Calculator();      
    String something= calculator.calculateM();

}

尝试从面向对象范式的角度来理解这一点。这个 class 代表一次旅行,并提供了一种基于它计算一些数字的方法。实例字段正在计算中使用。这表明该方法属于一个对象。因此,您应该创建 class 的对象,然后使用该对象调用该方法。这是一个片段:

Calculation c = new Calculation();
c.calculateM();

总的来说,您的方法似乎存在一些设计缺陷,但如果提供了有关 classes 和方法的更多信息,我只能建议替代方案。

您滥用了继承,这个根本问题导致您的代码无法运行。在你上面的class中你有

calculation extends tripCostCalculatorUI

你有计算 class 扩展 GUI,希望 GUI 字段可以在你的计算中使用,但这不是继承的目的 - 它不存在允许你连接数据,而是 扩展行为 。是的,您当前的继承设置将允许您访问 JTextFields,但是(这是关键),这些 JTextFields 与 GUI 中显示的相同,因为它们属于完全不同的实例。您的计算 class 不满足与 GUI class 的 "is-a" 关系,因此不应扩展它。

相反,您应该提供计算 class(应重命名为计算,因为所有 class 名称都应以大写字母开头)的方法,这些方法采用允许其他参数的数字参数classes 使用此 class,包括 Gui class,能够将数据传递到计算方法中,然后得到它们 return 的结果。

因此计算不应使用 JTextField 变量,而是使用传递到其计算方法参数中的值。

因此在 GUI 的 ActionListener 中,GUI 本身将从其组件中提取数据,将任何需要转换的内容转换为数值,从 Calculation class 中调用适当的方法进行计算,然后显示returned 的结果(将结果转换为文本后)。

这是一个简单的例子,说明了我的意思,其中 GUI 和计算 classes 是分开的,您在其中使用方法参数:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class SimpleCalcGui extends JPanel {
    private static final long serialVersionUID = 1L;
    private JTextField field1 = new JTextField(5);
    private JTextField field2 = new JTextField(5);
    private JTextField resultField = new JTextField(5);
    private JButton calcButton = new JButton("Calculate");

    public SimpleCalcGui() {
        resultField.setFocusable(false);
        calcButton.addActionListener(new CalcListener());

        add(field1);
        add(new JLabel("+"));
        add(field2);
        add(new JLabel("="));
        add(resultField);
        add(calcButton);
    }

    private class CalcListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                // extract the values and convert to numbers
                int value1 = Integer.parseInt(field1.getText());
                int value2 = Integer.parseInt(field2.getText());

                // call MyCalc's method passing in the values
                int result = MyCalc.addition(value1, value2);

                // display the result
                resultField.setText("" + result);

            } catch (NumberFormatException e1) {
                JOptionPane.showMessageDialog(calcButton, "Both text fields must have valid numbers",
                        "Numeric Entry Error", JOptionPane.ERROR_MESSAGE);
                field1.setText("");
                field2.setText("");
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }

    private static void createAndShowGui() {
        SimpleCalcGui mainPanel = new SimpleCalcGui();
        JFrame frame = new JFrame("SimpleCalcGui");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
}

public class MyCalc {
    // overly simple but just to show what I mean
    public static int addition(int value1, int value2) {
        return value1 + value2;
    }
}