Home > Enterprise >  Swing issue with running method from button action
Swing issue with running method from button action

Time:09-17

I am attempting to make a calculator using Swing but ran into some errors originally when trying to parse my strings from text fields into ints, then run a formula on them to calculate x's percentage of y ((x/y)*100).

I realized that I was having some issues first off because I was probably running a method that would need to return a double, so I fixed that. I then had to prefill my text fields with "1" because I was getting errors when they were set to "". Now when I try to run my program with say a test case of x=20, y=100, I still get "1 is 100 percent of 1". I assume for some reason there is an issue with my logic passing my updated values from the text fields so they are not being run through my calcdUp method.

Why would this method not be receiving these values? Is it because it is running before it is called?

package swingTest;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class swingWindow {

    private JFrame frame;
    private JTextField textField;
    private JTextField textField_1;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    swingWindow window = new swingWindow();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    
    public double calcdUp(double x, double y) {
        double calcd = (x/y)*100;
        return calcd;
    }

    /**
     * Create the application.
     */
    public swingWindow() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);
        
        JLabel lblNewLabel = new JLabel("Format: X is what percent of Y?");
        lblNewLabel.setBounds(10, 11, 414, 14);
        frame.getContentPane().add(lblNewLabel);
        
        JLabel lblNewLabel_1 = new JLabel("X:");
        lblNewLabel_1.setBounds(10, 36, 46, 14);
        frame.getContentPane().add(lblNewLabel_1);
        
        textField = new JTextField("1");
        textField.setBounds(66, 33, 86, 20);
        frame.getContentPane().add(textField);
        textField.setColumns(10);
        double numX = Double.parseDouble(textField.getText());
        
        JLabel lblNewLabel_2 = new JLabel("Y:");
        lblNewLabel_2.setBounds(10, 61, 46, 14);
        frame.getContentPane().add(lblNewLabel_2);
        
        textField_1 = new JTextField("1");
        textField_1.setBounds(66, 58, 86, 20);
        frame.getContentPane().add(textField_1);
        textField_1.setColumns(10);
        double numY = Double.parseDouble(textField_1.getText());
        
        JLabel results = new JLabel("Results will be shown here...");
        results.setBounds(10, 120, 414, 65);
        frame.getContentPane().add(results);
        frame.revalidate();
        frame.repaint();
        
        JButton submitBtn = new JButton("Calculate Percentage");
        submitBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                double result = calcdUp(numX,numY);
                results.setText(numX   " is "   result   " percent of "   numY);
            }
        });
        submitBtn.setBounds(10, 86, 142, 23);
        frame.getContentPane().add(submitBtn);
        
        
    }
}

screenshot1

CodePudding user response:

double numX = Double.parseDouble(textField.getText());

...

double numY = Double.parseDouble(textField_1.getText());

The above statements do nothing. You are attempting to get text from the text field BEFORE the user types anything.

Those statements need to be moved to the ActionListener, so you can get the text displayed in the text field at the time the button is clicked.

double numX = Double.parseDouble(textField.getText());
double numY = Double.parseDouble(textField_1.getText());
double result = calcdUp(numX,numY);
results.setText(numX   " is "   result   " percent of "   numY);

Also:

  1. Class names should start with an upper case character. Learn by example from the class names of the Java API.

  2. Don't use a null layout and setBounds(...). Swing was designed to be used with Layout Managers.

CodePudding user response:

The numX and numY variables are set once, to the default value of your textFields when you create them in your initialize() method. You need create numX and numY inside your actionPerformed method to get the current state of your components.

E.g.:

        JButton submitBtn = new JButton("Calculate Percentage");
        submitBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                double numX = Double.parseDouble(textField.getText());
                double numY = Double.parseDouble(textField_1.getText());
                double result = calcdUp(numX,numY);
                results.setText(numX   " is "   result   " percent of "   numY);
            }
        });

CodePudding user response:

JButton submitBtn = new JButton("Calculate Percentage");
submitBtn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        double numX = !textField.getText().isEmpty() ?  Double.parseDouble(textField.getText()) : 0;
        double numY = !textField_1.getText().isEmpty() ? Double.parseDouble(textField_1.getText()) : 0;

        double result = calcdUp(numX,numY);
        results.setText(numX   " is "   result   " percent of "   numY);
    }
});
submitBtn.setBounds(10, 86, 142, 23);
frame.getContentPane().add(submitBtn);
  • Related