0

I want to make a validation when the user clik the jbutton1 if the textboxt field empty the jlabel value will show "Input name cannot be empty". I'm beginner.

Here my false code :

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                      
        if(jTextField1.text == ""){
        jLabel1.setText("Input name cannot be empty");
        }else{
        jLabel1.setText("My name : " + jTextField1.getText() + ". Selamat datang di java .");
    }                             

4 Answers4

1

Use equals() instead of == as-

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                      
    if(jTextField1.equals(""){
    jLabel1.setText("Input name cannot be empty");
    }else{
    jLabel1.setText("My name : " + jTextField1.getText() + ". Selamat datang di java .");
}                             
1

Avoid using == as it is not correct. isEmpty() method will do the trick. Make sure to trim(); for removing any white spaces beforehand. Try to use this :

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                      
    if(jTextField1.getText().trim().isEmpty()){
        jLabel1.setText("Input name cannot be empty");
    } else {
        jLabel1.setText("My name : " + jTextField1.getText() + ". Selamat datang di java .");
    }
}  
GGO
  • 2,678
  • 4
  • 20
  • 42
Kevin
  • 407
  • 2
  • 7
  • 22
0

Use .equals() method of String instead of ==. To get Text from jTextField1 use getText() method.

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                      
    if(jTextField1.getText().equals(""){
    jLabel1.setText("Input name cannot be empty");
    }else{
    jLabel1.setText("My name : " + jTextField1.getText() + ". Selamat datang di java .");
}  

Check this What is the difference between == vs equals() in Java?

Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48
0

First, you need to replace all whitespace to check if the input has any characters and then compare the length or using .equals():

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {  
    String text = jTextField1.getText().replaceAll("\\s+","");
    if(text.length() <= 0){
    jLabel1.setText("Input name cannot be empty");
    }else{
    jLabel1.setText("My name : " + jTextField1.getText() + ". Selamat datang di java .");
}    
Thai Doan
  • 300
  • 3
  • 14