Search code examples
javajtextfieldjcheckboxitemlistener

Using an itemListener with JCheckBox to show/hide JTextField


I'm trying to create an application that allows a user to choose insurance options in JCheckBoxes. For each option that is selected, the name and price are supposed to appear in a text field. My problem is that even when I select it, it doesn't display the Name & Price. At the moment I'm just trying to make the HMO checkbox work.

package p3s4;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class JInsurance extends JFrame implements ItemListener
{       
        FlowLayout flow = new FlowLayout();
        final double HMO_PRICE = 200;
        final double PPO_PRICE = 600;
        final double DENTAL_PRICE = 75;
        final double VISION_PRICE = 20;
        JLabel heading = new JLabel("Choose insurance options: ");
        JCheckBox hmo = new JCheckBox("HMO");
        JCheckBox ppo = new JCheckBox("PPO");
        ButtonGroup providersGroup = new ButtonGroup();
        JCheckBox dental = new JCheckBox("Dental");
        JCheckBox vision = new JCheckBox("Vision");
        JTextField hmoSelection = new JTextField(hmo + " " + HMO_PRICE);
public JInsurance()
{
    super("Insurance Options");

    setLayout(flow);
    add(heading);
    providersGroup.add(hmo);
    providersGroup.add(ppo);
    add(hmo);
    add(ppo);
    add(dental);
    add(hmoSelection);
    hmoSelection.setVisible(false);
    add(vision);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    hmo.addItemListener(this);
}
public void itemStateChanged(ItemEvent event)
{
    if(event.getStateChange() == ItemEvent.SELECTED)
    {
            hmoSelection.setVisible(true);
    }    
    else
        hmoSelection.setVisible(false);
}
public static void main(String[] args) 
{
    JInsurance first = new JInsurance();
    final int WIDTH = 400;
    final int HEIGHT = 300;
    first.setSize(WIDTH, HEIGHT);
    first.setVisible(true);
}
}

Solution

  • Add the following code in your if block and it will work as expected

    hmoSelection.getParent().revalidate();
    

    The API docs for revalidate:

    Revalidates the component hierarchy up to the nearest validate root.

    This method first invalidates the component hierarchy starting from this component up to the nearest validate root. Afterwards, the component hierarchy is validated starting from the nearest validate root.

    This is a convenience method supposed to help application developers avoid looking for validate roots manually. Basically, it's equivalent to first calling the invalidate() method on this component, and then calling the validate() method on the nearest validate root.