Java JToggleButton-如何获取选定状态?

Java JToggleButton-如何获取选定状态?,java,swing,frame,jtogglebutton,Java,Swing,Frame,Jtogglebutton,我正在制作一个BMR计算器,我的一个面板为用户提供了一个选项,可以改变他们输入身高的方式,从厘米到英尺/英寸 下面是处理上述面板的代码块 // Height JComponents heightLabel = new JLabel("Height:"); heightCMField = new JTextField(4); heightFTField = new JTextField(3); heightFTLabel = new JLabel("ft")

我正在制作一个BMR计算器,我的一个面板为用户提供了一个选项,可以改变他们输入身高的方式,从厘米到英尺/英寸

下面是处理上述面板的代码块

    // Height JComponents
    heightLabel = new JLabel("Height:");
    heightCMField = new JTextField(4);
    heightFTField = new JTextField(3);
    heightFTLabel = new JLabel("ft");
    heightINCHLabel = new JLabel("inch");
    heightINCHField = new JTextField(3);
    cmButton = new JToggleButton("cm");
    feetButton = new JToggleButton("feet");
    heightPanel.add(heightLabel);


    if (cmButton.isSelected()) {
        heightPanel.add(heightCMField);
    } else if (feetButton.isSelected()) {
        heightPanel.add(heightFTField);
        heightPanel.add(heightFTLabel);
        heightPanel.add(heightINCHField);
        heightPanel.add(heightINCHLabel);
    } 

    heightPanel.add(cmButton);
    heightPanel.add(feetButton);
我的问题是,当我按下kg或cm按钮时,文本字段不会出现,因此我认为我使用的isSelected()有点错误

下面是一幅关于这种情况的图像。您可以看到,即使选择了脚,也不会显示任何文本字段。我能做些什么来解决这个问题


您需要添加一个侦听器:

cmButton.addActionListener(event->{

    /**
     * Code to show heightCMField.
     */
});

feetButton.addActionListener(event-> {

    /**
     * COde to show heightFTField and heightINCHField 
     */
});  
如果您使用的是
JToggleButton
,我想您只需要使用一个切换GUI的ToggleButton。因此,如果是这种情况,请删除
cmButton
feetButton
。并且只添加一个新的ToggleButton来完成这一切

JToggleButton switchButton = new JToggleButton();
switchButton.setText("cm");  

switchButton.addActionListener(event->{

    if(switchButton.getText().equals("feet")) {

        switchButton.setText("cm");
        /* Code to show heightFTField and heightINCHField */
    } else if(switchButton.getText().equals("cm")) {

        switchButton.setText("feet");
        /* Code to show heightCMField */
    }
});  

You can also go for `ItemListener`.

选择或未选择。您的GUI看起来应该是常规的JButtons。@GilbertLeBlanc我想将这些按钮分组为单选按钮,这样我就可以默认打开一个按钮,并且可以在它们之间切换。切换按钮可以吗?“我想像单选按钮一样对这些按钮进行分组,”使用
JRadioButton
(在
按钮组中)
)!此外,
重量:
高度:
年龄:
的字段可能都应该是一个
JSpinner
,带有
喷丝头编号模型
@androwthompson,我更喜欢切换按钮外观;我没办法让它们像单选按钮一样工作吗?我设法将它们组合在一起,以便在同一时间只能选择一个,但它不会检测到我何时从厘米切换到脚,反之亦然。此外,我还将研究JSpinner和SpinnerNumberModel。“我更喜欢切换按钮外观”,如果你是该应用程序的唯一用户,这可能与此相关。但在这种情况下,问题变得过于专业化,我无法关心。谢谢你,试着让我的头脑清醒过来。我想现在我会坚持使用2个切换按钮-我会用什么替换事件->呢?干杯,我似乎不能让这些工作,我不知道为什么。是我当前的代码,知道我做错了什么吗?事件->保持原样。您的代码需要转到注释部分。pastebin有什么问题?我像上面那样尝试了你的代码,但没有效果,似乎无法在actionListener方面取得任何效果。我应该补充一点,actionListener正在注册切换选择,但出于任何原因,这些项都没有添加到面板中
code
feetButton.addActionListener(新建ActionListener(){public void actionPerformed(ActionEvent e){System.out.println(“blah1”);heightPanel.add(heightFTField);heightPanel.add(heightFTLabel);heightPanel.add(heightINCHField);heightPanel.add(heightINCHLabel);})<代码>\code