0

I would like to control when a string form my textfield is empty or not. Here there's the code with a simple Swing interface:

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

public class Try{

public static void main(String[] args) {
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    panel.setLayout(null);
    JTextField text = new JTextField();
    JButton button = new JButton("ok");
    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            String get = "";
            get = text.getText();
            if ( get == "" ) System.out.println("Is not empty");
            else System.out.println("Is empty");
        }
    });

    panel.add(text);
    text.setBounds(0, 0, 50, 20);
    panel.add(button);
    button.setBounds(60, 0, 50, 20);

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(100,100);
    frame.getContentPane().add(panel);
    frame.setVisible(true);
  }
}

but also if you fill something in the texfield and then push the ok button, the if goes always on "is empty" ... so, the if is always false

What's wrong?!

user2123185
  • 37
  • 1
  • 4

2 Answers2

4

To compare Strings you have to use the .equals(String) function.

A String is an Object, therefore the == does compare the object reference of the two Strings .

But what you want is to compare the String value.

You should use

if ( "".equals(get) ) System.out.println("Is not empty");
Seega
  • 3,001
  • 2
  • 34
  • 48
1

Please try:

if (yourJTextField.getText().equals(""))
{
 ...
}
Seega
  • 3,001
  • 2
  • 34
  • 48
AtmiyaDas2014
  • 300
  • 1
  • 3
  • 25