问题描述
我正在尝试使用 if else 条件在我的代码中的文本框上添加验证
我在文本框中添加了focusListener,当我从文本框中移除焦点时,它会检查条件
我还在 chekBox 旁边创建了一个标签,它将根据条件显示文本
如果文本框内的文本不等于“hi”,则应在文本框旁边的标签中打印“hello”
否则应该打印“bye”
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import javax.swing.*;
public class regframe extends JFrame implements ActionListener
{
private static final long serialVersionUID = 1L;
JTextField t1,t2;
JLabel l1,l2,l3,l4;
JButton b;
regframe()
{
getContentPane().setBackground(Color.BLACK);
l1=new JLabel("Enter First Num:");
l1.setBounds(50,50,150,20);
l1.setForeground(Color.WHITE);
l1.setFont(new Font("Verdana",Font.BOLD,12));
add(l1);
t1=new JTextField();
t1.setBounds(180,100,20);
t1.setBackground(Color.BLACK);
t1.setForeground(Color.WHITE);
t1.setBorder(BorderFactory.createMatteBorder(0,1,Color.YELLOW));
t1.setCaretColor(Color.CYAN);
t1.setFont(new Font("Verdana",12));
t1.addActionListener(this);
add(t1);
l3=new JLabel();
l3.setBounds(290,20);
l3.setForeground(Color.CYAN);
l3.setopaque(false);
l3.setFont(new Font("Verdana",10));
add(l3);
t1.addFocusListener(new FocusAdapter()
{
public void focusLost(FocusEvent e)
{
if(t1.getText()!="hi")
{
l3.setText("hello");
}
else
{
l3.setText("bye");
}
}
});
l2=new JLabel("Enter Second Num:");
l2.setBounds(50,80,20);
l2.setForeground(Color.WHITE);
l2.setFont(new Font("Verdana",12));
add(l2);
t2=new JTextField();
t2.setBounds(180,20);
t2.setBackground(Color.BLACK);
t2.setForeground(Color.WHITE);
t2.setBorder(BorderFactory.createMatteBorder(0,Color.YELLOW));
t2.setCaretColor(Color.CYAN);
t2.setFont(new Font("Verdana",12));
add(t2);
b=new JButton("Submit");
b.setBounds(100,120,20);
b.setBackground(Color.CYAN);
b.setForeground(Color.BLACK);
add(b);
setLocation(300,200);
setSize(700,250);
setLayout(null);
setTitle("Registration");
setVisible(true);
setDefaultCloSEOperation(EXIT_ON_CLOSE);
}
public static void main(String args[])
{
new regframe();
}
public void actionPerformed(ActionEvent arg0)
{
}
}
但是当我运行代码时,即使我在文本框中写“hi”,它也总是显示“hello”
请帮忙
解决方法
使用
if(!"hi".equals(t1.getText())
代替
if(t1.getText()!="hi")
你也可以if(!t1.getText().equals("hi"))
但另一种方法更 null 安全