让选定的单选按钮显示在文本区

时间:2015-05-01 16:48:36

标签: java swing actionlistener jradiobutton

我在netbeans中创建一个程序,允许用户导入他们的计算机规格,我有2个单选按钮,当你选择选择时我想要它,当按下显示它会在文本区域显示你的选择。我已经有了其他文本字段,人们可以在其中输入信息显示在文本区域中,但是如何为单选按钮执行此操作。

  private void displayActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        textarea.append("Processor: " + processorTextField.getText() + "\nGraphics Card: "
           + graphicsCardTextField.getText() + "\nRam: " + ramTextField.getText() + "\nHard Drive: " + 
                   hardDriveTextField.getText() + "\nOperating System: " + operatingSystemTextField.getText()
                   + "\nMonitor Size: " + monitorTextField.getText());
    }  

这是我按下显示按钮时其他文本字段进入文本区域的代码

1 个答案:

答案 0 :(得分:1)

如果您已将JRadioButtons添加到ButtonGroup,则ButtonGroup可以通过调用 var constraintButton = NSLayoutConstraint (item: myButton, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 500) // Add the constraint to the view self.view.addConstraint(constraintButton) 来为您提供所选JRadioButton中的ButtonModel。然后你可以获得模型的actionCommand String(必须为JRadioButtons显式设置)。例如,假设一个名为buttonGroup的ButtonGroup:

getSelection()

例如:

private void displayActionPerformed(java.awt.event.ActionEvent evt) { 

    // 1st get the ButtonModel for the selected radio button
    ButtonModel buttonModel = buttonGroup.getSelection();

    // if a selection has been made, then model isn't null
    if (buttonModel != null) {  
        // again actionCommand needs to be set for each JRadioButton
        String actionCommand = buttonModel.getActionCommand();
        // TODO: use actionCommand String as needed
    }
}