Search code examples
javaswingmethodsdoublegettext

Java - Program will not Compile/method getText(double)


My program is suppose to make a GUI that calculates the square root of a number that is entered. I can not figure out why this code will not compile. I keep getting the following error message:

cannot find symbol symbol : method getText(double)

What am I doing wrong?

import java.awt.event.ActionEvent; //Next group of lines import various Java classes
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.GridLayout;
import java.text.*;

public class SquareRoot extends JFrame
{
    public static void main(String[] args) {
        //Creates Window
        JFrame frame = new JFrame();
        frame.setSize(450, 300);
        frame.setTitle("Find the Square Root");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel Numberlbl = new JLabel("Enter a number:");
        final JTextField NumberField = new JTextField(10);
        NumberField.setText("");

        JLabel Answerlbl = new JLabel("Square Root of your number is:");
        final JTextField AnswerField = new JTextField(10);
        AnswerField.setText("");

        JLabel ButtonLabel = new JLabel("Calculate Square Root");
        JButton button = new JButton("√");

        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(3,2));
        panel.add(Numberlbl);
        panel.add(NumberField);
        panel.add(ButtonLabel);
        panel.add(button);
        panel.add(Answerlbl);
        panel.add(AnswerField);
        frame.add(panel);

        class CalculateListener implements ActionListener {

            public void actionPerformed(ActionEvent event) {

                double NumberX = Double.parseDouble(NumberField.getText());
                double Answer = Math.sqrt(NumberX);
                AnswerField.setText(Answer);

            }
        }

        ActionListener listener = new CalculateListener();
        button.addActionListener(listener);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        }
    }

Solution

  • The only compilation error I got was for the AnswerField.setText() line - if you look at the API reference for setText() it takes a string, but you are trying to pass it a double.

    Have a look at the NumberFormat class for converting the double to a string correctly. A simpler option is to use a Double object (as opposed to the double data type, note capitalization), and use its toString() method. A down-and-dirty method is to write it as ("" + Answer), since it will auto-convert it for you.