用Java编辑单选按钮

时间:2013-04-02 10:36:58

标签: java swing jradiobutton buttongroup

我有GUI屏幕,可让您通过RadioButton从选择中设置联系人的隐私。虽然我可以像这样将数据添加到数据库......

 private void addContactButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        try {
            ContactDAO cDao = new ContactDAO();
            final ContactDTO cdto = new ContactDTO();


 String privacy = "";
            String alumni = "";
            if (all.isSelected()) {
                privacy = all.getText();
            }
            if (bio.isSelected()) {
                privacy = bio.getText();
            }
            if (none.isSelected()) {
                privacy = none.getText();
            }
            if (yes.isSelected()) {
                alumni = yes.getText();
            }
            if (no.isSelected()) {
                alumni = no.getText();
            }
            cdto.setAlumni(alumni);
            cdto.setStatus(privacy);
            cDao.add(cdto); 

}

我无法检索之前为编辑模式选择的项目。每个radiobutton选项属于buttongroup。

private void editContact() {
    txtID1.setText(String.valueOf(cDTO.getID()));
    txtTitle1.setText(cDTO.getTitle());
    txtFn1.setText(cDTO.getForename());
    txtSn1.setText(cDTO.getSurname());
    //get status from cDTO.getStaus and adjust appropriately to the radio button
}

在上面的方法中我想设置单选按钮的选定项目。就像你为JComboBox做getSelectedItem()一样,我试图为单选按钮实现相同的功能。 note cDTO包含数据字符串cDTO.getStatus,它从数据库中获取值。但是如何将其设置为我所拥有的3个单选按钮,名为allButton bioButton noneButton

1 个答案:

答案 0 :(得分:1)

假设cDTO.getStatus()返回与单选按钮名称匹配的String:对于ButtonGroupb中的每个按钮,请执行以下操作:

b.setSelected(cDTO.getStatus().equals(b.getText()));