JButton button = new JButton("Click me!"); button.setEnabled(false); // Disable the button System.out.println("Is button enabled? " + button.isEnabled()); // Output: false
JButton saveButton = new JButton("Save"); JTextField textField = new JTextField("Enter text here"); textField.getDocument().addDocumentListener(new DocumentListener() { @Override public void changedUpdate(DocumentEvent e) { saveButton.setEnabled(true); } @Override public void insertUpdate(DocumentEvent e) { saveButton.setEnabled(true); } @Override public void removeUpdate(DocumentEvent e) { if(textField.getText().equals("")){ saveButton.setEnabled(false); } } }); // Determine package library: javax.swing.JButtonIn this example, we create a new JButton and a JTextField. We add a DocumentListener to the text field which enables the saveButton whenever text is changed or inserted. However, the button is disabled again whenever the text field is empty. The package library used is javax.swing.JButton.