Pergunta

as I said in other posts I'm new in Java and I'm having some dumb problems, here's the deal:

I have a radioButton (radioStock) and a textField (stockField). I want stockField to be setEnabled(false) by default, no problem with that, and whenever the radioStock is checked, set the stockField enabled on true. I wrote this code, but it doesn't work.

if (radioStock.isSelected()) {
    stockField.setEnabled(true);
}else{
    stockField.setEnabled(false);
}
Foi útil?

Solução 2

This should work

    radioStock.addActionListener(new ActionListener() 
    {
    @Override
    public void actionPerformed(ActionEvent e) 
    {
         if(radioStock == e.getSource()) 
         {
            stockField.setEnabled(radioStock.isSelected());
         }
       }
    });

Outras dicas

That code needs to be in a listener that is attached to the JRadioButton such as an ActionListener or ItemListener. And you don't even need the if blocks since all you'd need is one line of code inside of the listener:

  radioStock.addItemListener(new ItemListener() {

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

For more on use of JRadioButtons, please check out the tutorial: button tutorial.


Edit my SSCCE

import java.awt.event.*;
import javax.swing.*;

public class ItemListenereg {
   private static void createAndShowGui() {
      final JRadioButton radioStock = new JRadioButton("Stock", true);
      final JTextField stockField = new JTextField(10);
      JPanel panel = new JPanel();
      panel.add(radioStock);
      panel.add(stockField);

      radioStock.addItemListener(new ItemListener() {

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

      JOptionPane.showMessageDialog(null, panel);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top