Skip to content
Advertisement

The methods setText() and getText() are undefined for the type String in Java?

I’m building a calculator with in Java by using Eclipse – Luna, but when adding the code of “Entering the number” I get two error messages as follow:

The Code:

    JButton btn8 = new JButton("8");
    btn8.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {

            String EnterNumber = TxtDisplay.getText() + btn8.getText();
            TxtDisplay.setText(EnterNumber );
        }
    });
    btn8.setFont(new Font("Tahoma", Font.BOLD, 18));
    btn8.setBounds(79, 137, 50, 50);
    frame.getContentPane().add(btn8);

The Error Messages:

The method getText() is undefined for the type String
The method setText(String) is undefined for the type String

Could anyone help me please?

Advertisement

Answer

If you are willing to display the content of TxtDisplay on GUI, that implies TxtDisplay has to be a JTextField.

Look up your code you’ll find String TxtDisplay; replace it by JTextField TxtDisplay;.

Once you do that you can access public methods of class JTextField such as getText() and setText(String).

Side note: Please next time choose a better title for your question, this is for your own benefit so our community can interact with you better.

Advertisement