我正在尝试创建一个应用程序,允许用户在 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/