-1

This looks like one of the 10000th similar topics but I just can't find something similar. I've spent enough time on this already not to ask you guys. What I'm trying to achieve is to use method "calculateM()" in another class. They both have required imports etc. The method returns String number. I'm not sure how to call it.

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();
}
Lazio
  • 105
  • 1
  • 10

4 Answers4

3

You are misusing inheritance, and this fundamental issue is causing your code not to work. In your class above you have

calculation extends tripCostCalculatorUI

you have the calculating class extend the GUI, with hopes that the GUI fields can then be used in your calculation, but this is not what inheritance is for -- it's not present to allow you to connect data, but rather to extend behavior. Yes, your current inheritance set up will allow you to access JTextFields, but (and this is key), these JTextFields are not the same as the ones displayed in the GUI, since they're part of a completely different instance. Your calculation class does not satisfy the "is-a" relationship with the GUI class, and so should not extend it.

Rather, instead you should give the calculation class (which should be renamed Calculation, as all class names should begin with an upper-case letter) methods that take numeric parameters that allow other classes that use this class, including the Gui class, the ability to pass data into the calculation methods, and then get the results that they return.

And so Calculation should use no JTextField variables and instead use the values passed into its calculation method parameters.

So within the GUI's ActionListener, the GUI itself will extract data from its components, convert anything that needs conversion to numeric values, call the appropriate method from the Calculation class to allow a calculation, and then display the result that is returned (after converting the result to text).

Here's a simple example of just what I mean where the GUI and the calculation classes are separate, where you use method parameters:

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;
    }
}
  • I don't understand what you mean by allowing the ability to pass data into calculation methods. That's what I'm trying to figure out. I know the "skeleton" of the program is complete garbage. – Lazio Aug 05 '17 at 17:53
  • @Lazio: your confusion is one that involves a basic understanding of what objects are and how inheritance works, and to fully understand this (which you need to do), you must re-review these chapters in your text or tutorial. The key concept is that you should not have the calculation extend the GUI, remove that statement completely, get all GUI components out of calculation, use parameters with your methods, and it will work. – DontKnowMuchBut Getting Better Aug 05 '17 at 17:55
  • Ok, I've used inheritance so the other class could use the methods from another. I'm not sure how they are going to know about each other's methods if they're not linked together somehow. – Lazio Aug 05 '17 at 17:59
  • @Lazio: please see edit to answer to see what I mean – DontKnowMuchBut Getting Better Aug 05 '17 at 18:07
  • Thank you! :) I get it now. – Lazio Aug 05 '17 at 18:36
0

Well, that call would be valid if you were calling this method from calculation class What you need to do is to instantiate an object like this:

tripCostCalculatorUI obj = new calculation();
obj.calculateM();
QuakeCore
  • 1,886
  • 2
  • 15
  • 33
0
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {       

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

}
Harish Barma
  • 624
  • 8
  • 15
0

Try to understand this in terms of the object oriented paradigm. This class represents a trip and provides a method to calculate some number based on it. The instance fields are being used in the calculation. This indicates that the method belongs to an object. Hence, you should make an object of the class and then call the method using the object. Here is a snippet:

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

There seem to be some design flaws in your approach in general, but I can only suggest alternatives if more information about the classes and methods is given.

  • It doesn't recognise my entries in the textboxes. I have the messagebox with "Fill in all the boxes. – Lazio Aug 05 '17 at 17:47