Java Swing GUI

How to Disable JButton when JTextField is Empty

In this tutorial, we are going to see how to disable JButton when JTextField is empty in Java. JButton is a subclass of AbstractButton class and it can be used to add platform-independent buttons in a Java Swing application. JTextField is a component that allows modifying a single line of text.

In this tutorial we are going to see how to disable JButton when JTextField is empty by using DocumentListener interface with removeUpdate(), insertUpdate() and changedUpdate() methods which is triggered when inserting, deleting, or modifying text in JTextField.


 

Java Program to Disable JButton when JTextField is Empty:
import javax.swing.*;
import javax.swing.event.*;

public class EnableBtn extends JPanel 
{
    private JTextField text = new JTextField(10);
    private JButton btn = new JButton("Button");

    public EnableBtn() {
        text.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void removeUpdate(DocumentEvent e) {
                checkBtn();
            }

            @Override
            public void insertUpdate(DocumentEvent e) {
                checkBtn();
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                checkBtn();
            }
        });

        btn.setEnabled(false);

        add(text);
        add(btn);
    }

    private void checkBtn() {
        boolean value = !text.getText().trim().isEmpty();
        btn.setEnabled(value);
    }

    private static void createAndShowGui() {
        EnableBtn panel = new EnableBtn();
        JFrame f = new JFrame("Disable JButton");
        f.getContentPane().add(panel);
        f.pack();
        f.setLocationByPlatform(true);
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(()->createAndShowGui());
    }
}

Output:


mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *