user3216802
user3216802

Reputation: 9

How to use JCheckBox to make JTextField editable and vice versa?

I am writing an application in Java and am using Netbeans IDE. I have set two JCheckBox (chk1 and chk2) and two JTextField (jtextfield1 and jtextfield2). I want that if I check chk1, jtextfield2 will be set to uneditable and if I chk2, jtextfield2 will be set to editable and vice versa.

How to use JCheckBox to make JTextField editable and vice versa?

With the code below, it works alright but if i check the chk2 all the text fields are set to uneditable.

private void ckDepoActionPerformed(java.awt.event.ActionEvent evt) {

   if(ckDepo.isSelected()){
   txtDeposit.setEditable(false);
   }
   else{

   txtWithdraw.setEditable(true);
   }

}                                      

private void ckWithdrawActionPerformed(java.awt.event.ActionEvent evt) {                                           
    transact="withdraw";
    if(ckWithdraw.isSelected()){
   txtWithdraw.setEditable(false);
   }
    else{
   txtDeposit.setEditable(true);
   }
}                                          

Upvotes: 0

Views: 884

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Suggestions:

  • I would use JRadioButtons all added to the same ButtonGroup. This way selecting one JRadioButton will unselect all the others.
  • I would give each JRadioButton an ItemListener that inside it enabled or disabled its adjacent JTextField.

For example:

import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.ButtonGroup;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class RadioBtnMayhem {
   private static final int COLUMNS = 10;

   public static void main(String[] args) {
      JPanel mainPanel = new JPanel(new GridLayout(0, 1));
      ButtonGroup btnGroup = new ButtonGroup();
      int fieldCount = 5;
      for (int i = 0; i < fieldCount; i++) {
         JRadioButton radioBtn = new JRadioButton();
         btnGroup.add(radioBtn);
         final JTextField textField = new JTextField(COLUMNS);
         textField.setEnabled(false);
         radioBtn.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
               textField.setEnabled(e.getStateChange() == ItemEvent.SELECTED);
            }
         });

         JPanel radioFieldPanel = new JPanel();
         radioFieldPanel.add(radioBtn);
         radioFieldPanel.add(textField);

         mainPanel.add(radioFieldPanel);
      }

      JOptionPane.showMessageDialog(null, mainPanel);
   }
}

Upvotes: 1

Related Questions