I am using Netbeans, and I want it so a text field is only editable when the user clicks the check box. I have it so when they select the check box it makes the text field editable, but how do I make it so when they de-select the check box the text field becomes un-editable again?
The code I used to make it editable is -
private void chk4By6MouseClicked(java.awt.event.MouseEvent evt) {
txt4By6.setEditable(true);
}
Use ItemListener, so that you can enable or disable the JTextField
depending on if JCheckBox
is SELECTED
or DESELECTED
respectively.
A sample program :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ModifyTextField
{
public static void createAndDisplayGUI()
{
JFrame frame = new JFrame("MODIFY TEXTFIELD");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
final JPanel contentPane = new JPanel();
final JTextField tfield = new JTextField(10);
tfield.setEnabled(false);
final JCheckBox cbox = new JCheckBox("Enable TEXTFIELD", false);
ItemListener itemListener = new ItemListener()
{
public void itemStateChanged(ItemEvent ie)
{
tfield.setEnabled(ie.getStateChange() == ItemEvent.SELECTED)
}
};
cbox.addItemListener(itemListener);
contentPane.add(cbox);
contentPane.add(tfield);
frame.getContentPane().add(contentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndDisplayGUI();
}
});
}
}
Outcome :
and