java - 使用带有 JCheckBox 的 itemListener 来显示/隐藏 JTextField

标签 java jtextfield jcheckbox itemlistener

我正在尝试创建一个应用程序,允许用户在 JCheckBoxes 中选择保险选项。对于选择的每个选项,名称和价格应该显示在文本字段中。我的问题是,即使我选择它,它也不会显示名称和价格。目前我只是想让 HMO 复选框发挥作用。

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);
}
}

最佳答案

在 if block 中添加以下代码,它将按预期工作

hmoSelection.getParent().revalidate();

revalidate 的 API 文档:

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.

关于java - 使用带有 JCheckBox 的 itemListener 来显示/隐藏 JTextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30086429/

相关文章:

swing - 选中其中的复选框时,如何防止JPopUpMenu消失?

java - 尝试运行 MediaRecorder.start() 方法时出现 "java.lang.RuntimeException: start failed."

java - 编写一个程序,从键盘读取字符,直到读取换行符 '\n'

java - 从 NER 获取全名

java - 以编程方式设置文本时 InputVerifier 未激活

Java Swing,尝试用图像图标复选框替换 JTable 中的 boolean 复选框

java - 如何将 Perl 脚本翻译为 Java?

java - JTextField 文本未更改

java - 如果字符串以负号开头,setText 将无法正常工作

java - 无法在 JScrollPane 内构建或显示带有复选框的 Swing JTable