This discussion is archived
14 Replies Latest reply: Nov 19, 2012 9:43 AM by KonTiki RSS

How To Enable/Disable JTextField At Runtime

KonTiki Newbie
Currently Being Moderated
I can disable/enable JTextFields before runtime by the usual

myTextField.setEnabled(false/true);

But what I really want to do is to have the code itself decide whether to enable or disable certain fields depending on selections made at other JComboBoxes.
The idea is to avoid a situation whereby a user enters data into a field that is not relevant to the other selections that they have already made on the GUI.
However, if the user changes his/her mind on which primary selection they want to make at the JComboBox, the disabled fields may be re-enabled for the new selection.

I have coded it so that my GUI program decides to enable or not on the basis of the selection made at the first JComboBox.
But that does not work - the redundant fields are not greyed out for corresponding selections.

I have coded it so that the additional fields are initially disabled, then re-enabled for certain selections from the primary JComboBox.
This does not work either - the JTextFields remain greyed out regardless !

What do I do ?

I use Java SE 1.7 .

Edited by: KonTiki on 15-Nov-2012 14:00
  • 1. Re: How To Enable/Disable JTextField At Runtime
    rp0428 Guru
    Currently Being Moderated
    >
    What do I do ?
    >
    Have you tried coding it this way?

    That should do it. Test it and post the results.
  • 2. Re: How To Enable/Disable JTextField At Runtime
    KonTiki Newbie
    Currently Being Moderated
    Can't do that as it's GUI run.

    And the code is part of an app that I am naturally unwilling to show.

    Besides, those familiar with this proccess ought be able to see what I may be doing wrong.
  • 3. Re: How To Enable/Disable JTextField At Runtime
    rp0428 Guru
    Currently Being Moderated
    >
    And the code is part of an app that I am naturally unwilling to show.

    Besides, those familiar with this proccess ought be able to see what I may be doing wrong.
    >
    The only one that can see what you don't post is you. Those familiar with the process don't do it wrong.

    Plenty of other people asking for help haven't had a problem showing the code that they need help with. It is your code that is wrong and if you don't post it no one can see what it is in your code that is wrong.

    It's a long established fact that setEnabled works on JTextFields and your own post shows that you have verified that. So if the setEnabled method is called and the text field is repainted it will display properly.
  • 4. Re: How To Enable/Disable JTextField At Runtime
    KonTiki Newbie
    Currently Being Moderated
    Fair enough.

    La mañana, I'll run up a dummy GUI giving the essence of this hassle.

    If it still won't go for me, then I'll post it here.
    If it does, I'll post where I went wrong -- unless it's ridiculous .
  • 5. Re: How To Enable/Disable JTextField At Runtime
    Kayaman Guru
    Currently Being Moderated
    Are you enabling/disabling on the event thread? That's the only thing my crystal ball came up with.

    Also, why so worried about posting code? Afraid we'll steal it?
  • 6. Re: How To Enable/Disable JTextField At Runtime
    KonTiki Newbie
    Currently Being Moderated
    Yeah, I am afraid of that.

    Here's the sort of thing I am doing - although in this example, I'm weighing a beast rather than what I am doing in my intended application !
    The idea is to only consider the weight of the head for the animal with the large head, the elephant.
    So the additional weight attributed to the head is done here by enabling a new field, headFactor, to accept a figure which is a % of the remaining weight estimate.

    This is a silly example, I know.
    But if you go to used car/motorcycle searching sites, you'll see new data fields opening up or being greyed out according to the choice of make or model that the user selects.
    The whole idea is to minimise what the user can enter -- this minimises the chance of data entry error.

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.text.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.lang.*;
    
    
    
    
    
    
    public class EnableTest extends JFrame implements ActionListener
    
    {     
         // Attributes :
         // ----------
         
    
         // Pi is needed as Java trig functions need radian arguments.
         
         private final double pi = Math.PI ;
    
         
         // Variables for the data fields :
              
         
         // Holding array for drop-down menu lists :
         
         private String[] animalTypeList = {"Choose Animal Type", "Monkey", "Tiger", "Elephant"}; 
    
         
         
         
         // Graphics attributes :
         // -------------------
         
         private JTextArea displayArea1 = new JTextArea(10, 45);
         private JComboBox animalTypeBox = new JComboBox(animalTypeList);
         private JTextField girthField = new JTextField(10);
         private JTextField foreToHindField = new JTextField(10);
         private JTextField headFactorField = new JTextField(10);
         private JButton displayWeightButton = new JButton("Display Weight");
         private JButton quitButton = new JButton("Quit");
         private JTextArea displayArea2 = new JTextArea(4, 45);               
         
         
         // Methods of the EnableTest class :
         // ----------------------------
         // ----------------------------
         
         
         // Constructor :
         // -----------
         
         public EnableTest()
         
         {
              setSize(600, 1000);
              setLocation(400, 100);
              setTitle("EnableTest");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setLayout(new FlowLayout());
              setVisible(true);
              getContentPane().setBackground(Color.cyan);
              BevelBorder raisedBevel = new BevelBorder(BevelBorder.RAISED);
              
              
              // Get rid of the Java coffee cup icon on the JFrame :
              
              Image icon = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB_PRE);
              this.setIconImage(icon);
              
              // Add components :
              
              displayArea1.setText("Welcome to EnableTest !" + "\n" 
               + "================" + "\n"
               + "This program estimates the weight of a beast from its measurements.");
              
              // Add the first display area :
    
              add(displayArea1);
              
              // Add data fields & add non-default format to them :
    
              add(animalTypeBox);
              animalTypeBox.setBorder(new TitledBorder("Animal Type"));
              add(girthField);
              girthField.setBorder(new TitledBorder("Girth (m)"));
              add(foreToHindField);
              foreToHindField.setBorder(new TitledBorder("Fore To Hind (m)"));
              add(headFactorField);
              headFactorField.setBorder(new TitledBorder("Head Factor (%)"));
              
              // Disable the head factor field until activated :
              
              headFactorField.setEnabled(false);
    
              
              // Then add the buttons & add non-default format to these :
              
              add(displayWeightButton);
              displayWeightButton.setBorder(raisedBevel);
              displayWeightButton.setBackground(Color.green);
              
              add(quitButton);
              quitButton.setBorder(raisedBevel);
              quitButton.setBackground(Color.green);          
              
              displayArea2.setText("");
              
              // Add scroll pane for the second display area :
              
              JScrollPane textScrollPane2 = new JScrollPane(displayArea2);
              add(textScrollPane2);
         
              // Now add action listeners to the buttons and drop-down lists:
              
              displayWeightButton.addActionListener(this);
    
              quitButton.addActionListener(this);
              animalTypeBox.addActionListener(this);
    
              headFactorField.setEnabled(false);
              
              
              
         }     
              
              
              /* Event handling code :   */
             // -------------------
         
              
              public void actionPerformed(ActionEvent e)
              {
                   if (e.getSource() == displayWeightButton )
                   {
                        // Check and extract input data from GUI :                    
                        
                        if (animalTypeBox.getSelectedItem() == "Choose Dial Type")
                        {
                             displayArea1.setText("You must choose the type of animal that you want.");
                        }
                        
                        if (girthField.getText().length() == 0 || !isNumeric(girthField.getText() ) )
                        {
                             displayArea1.setText("You must enter some figure for the beast's girth !.");
                        }
                        
                        if (foreToHindField.getText().length() == 0 || !isNumeric(foreToHindField.getText() ) )
                        {
                             displayArea1.setText("You must enter some figure for the beast's fore-to-hind !.");
                        }
                   
                        String animalType = (String) animalTypeBox.getSelectedItem();
                        
                        // For each type of dial desired, calculate the appropriate hour angles & shadow points :
                        
                        DecimalFormat df = new DecimalFormat("#.##");
                        
                        if (animalType == "Monkey")
                        {                         
                             // Disable non-relevant data fields :
                             
                             headFactorField.setEnabled(false);
                             
                             double girth = Double.parseDouble(girthField.getText() ) ;               
                             System.out.println(Double.parseDouble(girthField.getText() ));
                             
                             double foreToHind = Double.parseDouble(foreToHindField.getText() ) ;
                             System.out.println(Double.parseDouble(foreToHindField.getText() ) );
                             
                             // Estimate the weight of this animal based on girth and fore-to-hind :
                             
                             double weight = 2.0*pi*Math.pow((girth/(2.0*pi)), 2.0)*(foreToHind/2.0) ;
                             
                             displayArea2.setText("The " + animalType + "'s weight is : " 
                                                     + df.format(weight) + " tonnes");
                        
                        }
                        
                        
                        if (animalType == "Tiger")
                        {                         
                             // Disable non-relevant data fields :
                             
                             headFactorField.setEnabled(false);
                             
                             double girth = Double.parseDouble(girthField.getText() ) ;               
                             System.out.println(Double.parseDouble(girthField.getText() ));
                             
                             double foreToHind = Double.parseDouble(foreToHindField.getText() ) ;
                             System.out.println(Double.parseDouble(foreToHindField.getText() ) );
                             
                             // Estimate the weight of this animal based on girth and fore-to-hind :
                             
                             double weight = 2.0 *pi*Math.pow((girth/(2.0*pi)), 2.0)*(foreToHind/2.0) ;
                                    
                             
                             displayArea2.setText("The " + animalType + "'s weight is : " 
                                      + df.format(weight) + " tonnes");
                        }
                        
                        
                        if (animalType == "Elephant")
                        {                         
                             // Enable all relevant data fields :
                             
                             headFactorField.setEnabled(true);
                             
                             if (headFactorField.getText().length() == 0 || !isNumeric(headFactorField.getText() ) )
                             {
                                  displayArea1.setText("You must enter some figure for the beast's head factor !");
                             }
                             
                             double girth = Double.parseDouble(girthField.getText() ) ;               
                             System.out.println(Double.parseDouble(girthField.getText() ));
                             
                             double foreToHind = Double.parseDouble(foreToHindField.getText() ) ;
                             System.out.println(Double.parseDouble(foreToHindField.getText() ) );
                             
                             double weight = 2.0*pi*Math.pow((girth/(2.0*pi)), 2.0)*(foreToHind/2.0) ;
                             System.out.println("Weight of " + animalType + " is : " + weight);
                             
                             // Add in head factor (%) assigned :
                             
                             double headFactor = Double.parseDouble(headFactorField.getText() ) ;
                             
                             weight = weight*(1+ headFactor/100.0) ;
                             
                             displayArea2.setText("The " + animalType + "'s weight is : " 
                                      + df.format(weight) + " tonnes");
                             
                        }
                        
                   }
                   
                   if (e.getSource() == quitButton )
                   {
                        System.exit(0);
                   }
                   
              }
    
    
              
              /** A simple method check to assure if a string is numeric or not. */
                        
              public static boolean isNumeric(String str)  
              {  
                try  
                {  
                  double d = Double.parseDouble(str);  
                }  
                catch(NumberFormatException nfe)  
                {  
                  return false;  
                }  
                return true;  
              }
         
         }  
    Now the above code "works" - but not as I'd like it to.
    It only disables/enables the headFactor data field after one clicks the display button.
    And if I make the headFactor field enabled from the outset, then it will appear enabled even if the animal chosen is a monkey or a tiger. This will confuse the user, who will try to enter a number into this field when he/she should not.

    So I want it to be enabled/disabled immediately after the animal is chosen.
    Is there a way to do this ?

    Edited by: KonTiki on 16-Nov-2012 13:17

    Edited by: KonTiki on 16-Nov-2012 13:25
  • 7. Re: How To Enable/Disable JTextField At Runtime
    rp0428 Guru
    Currently Being Moderated
    >
    Now the above code "works" - but not as I'd like it to.
    It only disables/enables the headFactor data field after one clicks the display button.
    And if I make the headFactor field enabled from the outset, then it will appear enabled even if the animal chosen is a monkey or a tiger. This will confuse the user, who will try to enter a number into this field when he/she should not.

    So I want it to be enabled/disabled immediately after the animal is chosen.
    Is there a way to do this ?
    >
    Thanks for posting the code. You only have one listener and you say to use it to listen for the 'animalTypeBox'
    animalTypeBox.addActionListener(this);
    But the reason that
    It only disables/enables the headFactor data field after one clicks the display button.
    Is because the code in the listener only does something 'after one clicks the display button'!
    if (e.getSource() == displayWeightButton )
    Want to guess at what 'e.getSource()' equals when the 'animalTypeBox' combo selection is made and the actionlistener is called?

    Hint: it won't be equal to 'displayWeightButton'.

    If you want the listener to act when an animal choice is made you need to include code in the listener that does something when the source is the combo box.

    If I add this code to the top of the listener the 'headFactorField' gets enabled just fine.
              public void actionPerformed(ActionEvent e)
              {
                        if (e.getSource() == animalTypeBox )
                        {
                   String animalType = (String) animalTypeBox.getSelectedItem();
                   // Enable all relevant data fields :
                   if (animalType == "Elephant")
                   {
                                headFactorField.setEnabled(true);
                            }
                            return;
                        }
                        if (e.getSource() == displayWeightButton )
    . . .
    Now do you see why we need to see the source code to see what you are doing?

    I'll leave it as an excercise for you to factor out the enable/disable code appropriately based on the above example. If you use the same listener for multple things you need to include code that executes based on the source of the action.
  • 8. Re: How To Enable/Disable JTextField At Runtime
    KonTiki Newbie
    Currently Being Moderated
    OK.

    I'd assumed that only buttons could be made to 'listen' to the mouse, not data fields.
    The parameterless return statement is also something I'd not thought of to effect the changes to the GUI
    immediately after changes to the JComboBox selection.

    Works smooth as silk now.

    Thanks.

    Happy weekend, hombre.
    Over and out.

    KonTiki.

    P.S. No, I am not weighing animals in my application.

    Edited by: KonTiki on 18-Nov-2012 06:32

    Edited by: KonTiki on 18-Nov-2012 15:39

    Edited by: KonTiki on 26-Nov-2012 05:58
  • 9. Re: How To Enable/Disable JTextField At Runtime
    Kayaman Guru
    Currently Being Moderated
    KonTiki wrote:
    P.S. No, I am not weighing animals in my application.
    P.S. Nobody is going to steal application code posted in New To Java (or anywhere else for that matter).
  • 10. Re: How To Enable/Disable JTextField At Runtime
    KonTiki Newbie
    Currently Being Moderated
    I mean they would steal the idea of the application.
  • 11. Re: How To Enable/Disable JTextField At Runtime
    Kayaman Guru
    Currently Being Moderated
    KonTiki wrote:
    I mean they would steal the idea of the application.
    I think other people stealing the idea or code is the least of your worries. One of the biggest would be that you simply don't have the experience to finish your product.
  • 12. Re: How To Enable/Disable JTextField At Runtime
    KonTiki Newbie
    Currently Being Moderated
    Well !
    Kiitos, Kayaman.

    I could give many answers to that comment.

    But I think that the best response is simply :

    Let's see how it works out !

    And you have a nice day, Buddy . . .
    Seems you need it !

    Edited by: KonTiki on 19-Nov-2012 08:54

    Edited by: KonTiki on 19-Nov-2012 08:55
  • 13. Re: How To Enable/Disable JTextField At Runtime
    TPD-Opitz-Consulting-com Expert
    Currently Being Moderated
    KonTiki wrote:
    Well !
    Kiitos, Kayaman.
    I could give many answers to that comment.
    But I think that the best response is simply :
    Let's see how it works out !
    OK, let's see:
    You asked for help on a rather simple problem. (This is ok for a beginner)
    And you have a nice day, Buddy . . .
    Seems you need it !
    You're wearing your head a little too high compared to the problem you have.

    So I for myself would not bet my money on you...

    bye
    TPD
  • 14. Re: How To Enable/Disable JTextField At Runtime
    KonTiki Newbie
    Currently Being Moderated
    Kayaman is big enough to look after himself, TPD.

    And you are old enough to know why third parties should stay out of clashes.

    Although, after 50 laps of the sun, I'd hardly see it as all that much.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points