Search code examples
javaswingjtextfieldjcombobox

JTextField with JComboBox is not working properly


I want a JTextField to appear when user select "Extra" in JComboBox list and hidden otherwise. But the JTextField is not appearing when user is selecting "Extra" but it is appearing if i shrink the window and enlarge it again. After doing like that it is working properly, only for the first time it is not appearing. Why it is behaving like that? any solution for this?

Here is my code:

getCmbJtocsv_C_8().addActionListener(new ActionListener() { 
   public void actionPerformed(ActionEvent e) {
   {

      input3 = (String)adaptor.getCmbJtocsv_C_8().getSelectedItem();
      adaptor.getTxtJtocsv_C_8().setVisible(false);

      if(input3.equals("extra")){
          adaptor.getTxtJtocsv_C_8().setVisible(true);
      }
}

i have changed the string comparison and i'm still getting the same result.


Solution

  • By default Swing components have a size of (0, 0). The size/location of a component is determined by the layout manager when the frame is packed or made visible.

    So I would guess that since you start with the text field invisible the size of its parent panel does not include the text field. When you resize the frame the text field appears because its size and the size of the panel is recalculated.

    Now the size of the text field has been calculated so you can toggle the visibility as required.

    If this doesn't help then post a SSCCE that demonstrates the problem. That is create a frame with only a combo box and text field to demonstrate the problem. In the future all questions should contain a SSCCE since we can't guess the context of your application based on a few lines of code.