Enable/disable a Java swing button in relation with a combo box - java

How can I update the state (enable/disable) of my button when the user changes the selected item in a combo box.?
The button has a reference to the combo box, but the combo box does not know anything about the button.

If the button has a reference to the combo box, then the button can register an action listener at the combo box in which you can change the state of your button.
final JButton button = new JButton();
final JComboBox comboBox = new JComboBox();
comboBox.addActionListener( new ActionListener() {
#Override
public void actionPerformed( final ActionEvent event ) {
// Your logic to determine when to enable/disable:
final boolean enabled = comboBox.getSelectedIndex() == 0;
button.setEnabled( enabled );
}
} );

The combobox is not required to know about the button. You need to add a listener to the combobox events like this:
public class ComboBoxDemo ... implements ActionListener {
. . .
petList.addActionListener(this) {
. . .
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String petName = (String)cb.getSelectedItem();
yourButton.setEnabled(true/false);
}
. . .
}

The JButton could simply add its own ActionListener on the JComboBox and in the ActionListener you could then change the state of the JButton according to the selected item of the combo box.

I have previously written code where enabling or disabling a button depends on filling a textfield and selecting an item of a combobox together. It may be helpful here.
jComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jComboBoxActionPerformed(e);
}
});
...
jTextField.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
jTextFieldDocumentListener(e);
}
public void removeUpdate(DocumentEvent e) {
jTextFieldDocumentListener(e);
}
public void changedUpdate(DocumentEvent e) {
jTextFieldDocumentListener(e);
}
});
jTextField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jTextFieldActionPerformed(e);
}
});
...
private void jComboBoxActionPerformed(ActionEvent e){
if(jComboBox.getSelectedIndex() == -1)
jButton.setEnabled(false);
else if(!jTextField.getText().equals(""))
jButton.setEnabled(true);
}
private void jTextFieldDocumentListener(DocumentEvent e){
if(jTextField.getText().equals("") || jComboBox.getSelectedIndex() == -1){
jButton.setEnabled(false);
}
else{
jButton.setEnabled(true);
}
}
private void jTextFieldActionPerformed(ActionEvent e){
if(jTextField.getText().equals("")){
jButton.setEnabled(false);
}
if(!(jTextField.getText().equals(""))){
jButton.setEnabled(true);
}
}
If the combobox is selected and the textfield is filled, then the button will be enabled. Otherwise it will not be enabled.

Related

Checkbox disabled Combobox in Java [duplicate]

How can I make the comboBox available when the checkBox was uncheck (vice versa)
Why the comboBox is still disable after I unChecked the checkBox?
choice [] = {"A","B","C"};
JComboBox a = new JComboBox(choice);
JCheckBox chk = new JCheckBox("choice");
...
a.addActionListener(this);
chk.addActionListener(this);
...
public void actionPerformed(ActionEvent e) {
//disable the a comboBox when the checkBox chk was checked
if(e.getSource()==chk)
a.setEnabled(false);
//enable the a comboBox when the checkBox chk was unchecked
else if(e.getSource()!=chk)
a.setEnabled(true);
}
If I understand you correctly I think all that you need to do is to change the enabled state of the combo box based on the current value of the checkbox:
public void actionPerformed(ActionEvent e) {
if (e.getSource()==chk) {
a.setEnabled(chk.isSelected());
}
}
I have a similar set up, and I use an Item Listener, like so:
CheckBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange()==ItemEvent.SELECTED){
ComboBox.setEnabled(true);
}else if(e.getStateChange()==ItemEvent.DESELECTED){
ComboBox.setSelectedIndex(-1);
ComboBox.setEnabled(false);
}
}
});
This way the behaviour is different when selected and deselected.
I treid this and worked..
public class JF extends JFrame implements ActionListener {
String choice [] = {"A","B","C"};
JComboBox a = new JComboBox(choice);
JCheckBox chk = new JCheckBox("choice");
JF()
{
this.add(a, BorderLayout.NORTH);
this.add(chk, BorderLayout.CENTER);
setDefaultCloseOperation(EXIT_ON_CLOSE);
a.addActionListener(this);
chk.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
//NOTE THE FOLLOWING LINE!!!!
if(e.getSource()==chk)
a.setEnabled(chk.isSelected());
}
public static void main(String[] args) {
new JF().setVisible(true);
}
}
Your old code didn't work because, even unchecking a checkbox triggers the event. The source of the trigger is the checkbox.. so both while checking and unchecking the event source was chk
if (e.getSource() == chckbxModificar) {
if (chckbxModificar.isSelected()) {
cbxImpuesto.setEnabled(true);
cbxMoneda.setEnabled(true);
txtPorcentaje.setEditable(true);
txtSimbolo.setEditable(true);
} else {
cbxImpuesto.setEnabled(false);
cbxMoneda.setEnabled(false);
txtPorcentaje.setEditable(false);
txtSimbolo.setEditable(false);
}
}

Java Swing how to define multiple focus listeners on JTextFields but with different button actions

I am making JTextFields which should be populated when click on a button.
Suppose for an example:
txtField1.addFocusListener(new FocusListener() {
JTextField field = txtField1;
#Override
public void focusGained(FocusEvent e) {
btnMain_0.addActionListener(ee -> {
if (field.getText().length() > 4)
return;
else
field.setText((field.getText() + "0"));
});
}
#Override
public void focusLost(FocusEvent e) {
}
});
txtField2.addFocusListener(new FocusListener() {
JTextField field = txtField2;
#Override
public void focusGained(FocusEvent e) {
btnMain_0.addActionListener(ee -> {
if (field.getText().length() > 4)
return;
else
field.setText((field.getText() + "0"));
});
}
#Override
public void focusLost(FocusEvent e) {
}
});
But if I click on txtField1 and press btnMain_0, it enter 0.
Then if I click on txtField2 and press btnMain_0, it enter 00 (it considered pressing btnMain_0 two times).
How I can make it? Is there better solution two run listeners from list of jtextfields?
You can define a custom TextAction and add it to your buttons.
The TextAction allows you to track the last text component that had focus (before you click on the button).
Something like:
class KeyboardAction extends TextAction
{
private String letter;
public KeyboardAction(String letter)
{
super(letter);
this.letter = letter;
}
public void actionPerformed(ActionEvent e)
{
JTextComponent component = getFocusedComponent();
component.setCaretPosition( component.getDocument().getLength() );
component.replaceSelection( letter );
}
}
You then use the class like:
jButton1 = new JButton( new KeyboardAction("1") );
jButton2 = new JButton( new KeyboardAction("2") );
or you add the Action to an existing button by using:
button.setAction( new KeyboardAction("1") );

Add two buttons if another button has been pressed

b.button1 = new JButton("Deal");
b.button1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//code
b.button2 = new JButton("Hit");
panel.add(b.button2);
panel.validate();
b.button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//code
}
});
b.button3 = new JButton("Stay");
panel.add(b.button3);
panel.validate();
b.button3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//code
}
}
});
So I want The Buttons Hit and Stay to be added as soon as the Deal button has been pressed. I searched for a solution and found the panel.validate() method. I used it but now if I press the Deal button it only adds the Hit button.
You could add the buttons before and make them "hidden". If you press the button, you can "show" them to include them.

how to get a value from a Jcombobox array using a anonymous class

I have a array of Jradiobuttons.i am trying to have java anonymous class that implement ActionListener so when the user press on a radio button I can do something but since this is an array i cant give the array index using a while loop so how to identify what Jradiobutton I am using.and I want to get the text of that radio button and save it in a another variable...How can I do this?
This is what so far I have done :
if(count!=0) {
rs=pst.executeQuery();
JRadioButton a []=new JRadioButton[count];
jPanel3.setLayout(new GridLayout());
int x=0;
ButtonGroup bg=new ButtonGroup();
while(rs.next()) {
a[x]=new JRadioButton(rs.getString("name"));
bg.add(a[x]);
jPanel3.add(a[x]);
a[x].setVisible(true);
a[x].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,a[x].getText()); //here i cant use this x...even though i make x global value of x always will be 6 becouse of while loop.
}
});
x++;
}
}
If i understand you correctly, You can set the name of radio button:
a[x]=new JRadioButton(rs.getString("name"));
a[x].setName(rs.getString("name"));
and in ActionPerformed you get the source of action:
public void actionPerformed(ActionEvent e) {
if( e.getSource() instanceof JRadioButton){
String selectedRadioName = ((JRadioButton) e.getSource()).getName();
JOptionPane.showMessageDialog( null, selectedRadioName );
}
You could...
Supply each JRadioButton with a ActionCommand which will be made available via the ActionEvent
a[x]=new JRadioButton(rs.getString("name"));
a[x].setActionCommand(String.valueOf(x));
//...
a[x].addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
int value = Integer.parseInt(cmd);
JOptionPane.showMessageDialog(null, a[value].getText());
}
});
See How to Use Buttons, Check Boxes, and Radio Buttons for more details
You could...
Use the Action API to surround the message and action in a self contained unit of work...
public class MessageAction extends AbstractAction {
private String message;
public MessageAction(String text, String message) {
this.message = message;
putValue(NAME, text);
}
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, message);
}
}
And then apply it to your button something like...
a[x] = new JRadioButton(new MessageAction(rs.getString("name"), "Hello from " + x);
See How to Use Actions for more details.

ComboBox with ActionListener and if-statement

I'm trying to add an ActionListener to my ComboBox. I want to open a form when a item is selected from the box. I successfully implemented it on a JButton but I can't figure out how to do it in a combobox. Can someone please help me out?
JComboBox<String> valBox = new JComboBox<>();
valBox.addItem("Apparat");
valBox.addItem("Smycke");
valBox.addItem("Aktie");
södra.add(valBox);
valBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (valBox.getSelectedIndex() == 0)
nyLyss.ApparatForm.form1();
}
});
The code that I wan't to execute when the first item is selected is this one:
class nyLyss implements ActionListener{
public void actionPerformed(ActionEvent ae) {
try{
ApparatForm form1 = new ApparatForm();
int svar = JOptionPane.showConfirmDialog(Layout.this, form1);
if(svar != JOptionPane.OK_OPTION)
return;
String namn = form1.getNamn();
int inköpspris = form1.getPris();
int slitage = form1.getPris();
// saker ap = new saker(namn, inköpspris, slitage);
// alla.add(ap);
}catch(NumberFormatException e){
JOptionPane.showMessageDialog(Layout.this, "Felaktig indata!");
}
}
}
Thanks! :)
I would solve the problem with a ItemStateChanged listener on my combobox. Here a short example with a combobox called "mycombobox".
private void mycomboboxItemStateChanged(java.awt.event.ItemEvent evt) {
System.out.println(mycombobox.getSelectedItem());
}
The result is, that the application is printing out the selected item after every change of the selected item in the combobox "mycombobox".

Categories