【问题标题】:Java TextField getText() give me a string that I can't compare [duplicate]Java TextField getText()给我一个我无法比较的字符串[重复]
【发布时间】:2014-08-05 10:04:57
【问题描述】:

我想控制我的文本字段中的字符串何时为空。这里有一个简单的 Swing 界面的代码:

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);
  }
}

但如果你在 texfield 中填写一些内容然后按下 ok 按钮,if 总是打开“是空的”......所以,if 总是 false

怎么了?!

【问题讨论】:

  • 当你通过代码确定它不为空时打印出“is empty”

标签: java string swing listener textfield


【解决方案1】:

要比较字符串,您必须使用.equals(String) 函数。

字符串是对象,因此== 确实比较了两个字符串的对象引用。

但你想要的是比较字符串值。

你应该使用

if ( "".equals(get) ) System.out.println("Is not empty");

【讨论】:

    【解决方案2】:

    请尝试:

    if (yourJTextField.getText().equals(""))
    {
     ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-14
      • 2012-06-19
      相关资源
      最近更新 更多