Unfortunately, I cannot turn on .setEnable() for a JTextField, or a JTextField (tried both). It keeps remaining gray, so users cannot type. Please help me out.
Details: taTwo can be either a JTextField or JTextArea but any I try cannot be enabled. It should be disabled for A but should be enabled for B, so if user choose A he/she can NOT enter a value in taTwo field, but if the user choose B he/she can write in taTwo.
The method is the following:
public void btnAddtreeAction() {
this.btnAddtree.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JPanel dialogPanel = new JPanel();
dialogPanel.setPreferredSize(new Dimension(60,60));
String[] choices = {"A", "B"};
JComboBox<String> cb = new JComboBox<String>(choices);
JTextArea taOne = new JTextArea(1,30);
JTextField taTwo = new JTextField();
taTwo.setEnabled(false);
Object[] myObject = {"Options:", cb,
"Input first:", taOne,
"Input second:", taTwo};
JOptionPane.showConfirmDialog(frame, myObject, "Form", JOptionPane.OK_CANCEL_OPTION);
if (cb.getSelectedItem().toString().equals("A")) {
//something will happen here
} else if (cb.getSelectedItem().toString().equals("B")) {
taTwo.setEnabled(true);
//something will happen here
}
}
});
}
CodePudding user response:
In your actionPerformed
method, you are creating a new JTextField
which you are not adding to your GUI. I presume that you have another variable named taTwo
somehere in the code that you did not post. You are not changing that variable inside the actionPerformed
method. Try removing this line of your code:
JTextField taTwo = new JTextField();
CodePudding user response:
If I correctly understand your question, you need to move your enablemet/disablement code into another ActionListener
and add it to your combobox. Something like this:
public void btnAddtreeAction() {
this.btnAddtree.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JPanel dialogPanel = new JPanel();
dialogPanel.setPreferredSize(new Dimension(60,60));
String[] choices = {"A", "B"};
JComboBox<String> cb = new JComboBox<String>(choices);
JTextArea taOne = new JTextArea(1,30);
JTextField taTwo = new JTextField();
taTwo.setEnabled(false);
cb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (cb.getSelectedItem().toString().equals("A")) {
taTwo.setEnabled(false);
//something will happen here
} else if (cb.getSelectedItem().toString().equals("B")) {
taTwo.setEnabled(true);
//something will happen here
}
}
});
Object[] myObject = {"Options:", cb,
"Input first:", taOne,
"Input second:", taTwo};
JOptionPane.showConfirmDialog(frame, myObject, "Form", JOptionPane.OK_CANCEL_OPTION);
}
});
}