如何根据从数据库中获取的值设置单选按钮

时间:2015-07-22 06:57:57

标签: java swing jtable jradiobutton

我有JTable填充了有关students (student id, name...)的数据,当我从表格中选择一行时,表单会打开,其字段需要填充相同的值(例如,如果Johny Bravo从表中选出。

然后他的名字应该在表格上的文字档名中显示,我确实喜欢这个txtfieldName.setText(student.getName)

我的问题是当我点击字段时如何自动设置Radio button(我的单选按钮是男性或女性)。

enter code here

tableGuest.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
    try{
        int row = tableGuest.getSelectedRow();
        String guestEdit=(tableGuest.getModel().getValueAt(row,     0).toString());


        String query = "Select guest_id,guest_fname,guest_lname,guest_contact,guest_age,guest_gender,guest_address,guest_email from guest_tbl where guest_id= '"+guestEdit+"'";

    PreparedStatement pst = con.prepareStatement(query);
    ResultSet rs = pst.executeQuery();

    buttonGroupEdit.add(rdbtnMaleEdit);
    buttonGroupEdit.add(rdbtnFemaleEdit);


                while(rs.next())
                {
                    String genderEdit=rs.getString("guest_gender"); 

                    if(genderEdit.equals("Male"))
                    {
                         rdbtnMaleEdit.setSelected(true); 
                    }
                    else if(genderEdit.equals("Female"))
                    {
                         rdbtnFemaleEdit.setSelected(true);
                    }
                    else
                    {
                    JOptionPane.showMessageDialog(null, "error !");
                    }


                    tfEditFname.setText(rs.getString("guest_fname"));
                    tfEditLname.setText(rs.getString("guest_lname"));
                    tfEditEmail.setText(rs.getString("guest_email"));

                    tfEditContact.setText(rs.getString("guest_contact"))
                }
                pst.close();


            }catch(Exception ex){
                ex.printStackTrace();
            }

        }
    });

3 个答案:

答案 0 :(得分:0)

    String gender = "male" 
    // this comes from db - since we don't know the structure this is a plain guess.

    if (gender.equals("male") {
        rbtMale.setSelected(true); 
    } else {
        rbtFemale.setSelected(true); 
    } 

就像MadProgrammer说的那样,你需要一个ButtonGroupadd所有相关的按钮。

private final ButtonGroup genderButtons = new ButtonGroup();
genderButtons.add(rbtMale);
genderButtons.add(rbtFemale);

答案 1 :(得分:0)

我在工作中使用相同的解决方案我正在使用数据库值生成radiobutton并在java对话框中显示它们。

我们有一个存储在列表中的数据库的值,如下所示:

  

列出标题; //这是一个包含数据库值的列表

首先计算此列表元素的值:

  

int list_count = Titles.size();

现在首先要继续使用无线电功能,我们需要将列表元素转换为如下所示的数组:

String[] col = new String[list_count]; //created an array with limit of list count values
for(int i=0; i < list_count; i++){ 
col[i]=Titles.get(i).toString(); // add values of list into array with loop
}

以下是使用我们在上面创建的数据库数组创建单选按钮的功能:

 public String get_key(int list_count, String[] col){

   JRadioButton jb[] = new JRadioButton[col.length]; //Create Radion button array

   ButtonGroup rb = new ButtonGroup(); //Group Radio Button

   JPanel panel = new JPanel( new GridLayout(0, 1) ); //Set layout of radion button to display each after other

   JScrollPane sp = new JScrollPane(panel); // Create a scrollpane to put all these radio button on that

   GridBagLayout gridbag = new GridBagLayout(); //Layout for scrollpane

sp.setViewportBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); //bordre for scrollpane

    List<Component> q = new ArrayList<>(); // q is a component to store and display each radio button

    JLabel h1=new JLabel("Select a value"); //put a heading on top of jpanel before radio button

    h1.setFont(new Font("Serif", Font.BOLD, 18)); // set heading text

    panel.add(h1); //add heading on top of jpanel

    panel.setBorder(new EmptyBorder(10, 10, 10, 10)); //set panel border to padding each radio button

    for(int i=0; i < list_count; i++){ 

     jb[i]=new JRadioButton(col[i]); //create radion button dynamacially "col[i]" is the value of each radio

     rb.add(jb[i]); //it is important also to put all radio in a group we created so only one element should be selected

     panel.add(jb[i]); // add all radio on jpanel

        }

sp.setPreferredSize( new Dimension( 350, 300 ) ); //set size of scrollpane

int act=JOptionPane.showConfirmDialog(null, sp, "Select Primary Key",JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE); //add and show scrollpane in dialog

}

使用我们先创建的参数值调用此函数&#34; list_count&#34; &安培; &#34; COL&#34;:

get_key(list_count, col);

答案 2 :(得分:0)

创建一个Student.java类,以从数据库中获取特定的表值。 在当前表单AddStudent中,以getStudentList的形式创建函数调用,以使用特定ID的数据库数据填充GUI表单。

    public ArrayList<Student> getStudentList() {
    ArrayList<Student> studentList = new ArrayList<>();
    conn = DbConnection.ConnectDb();
    String selectQuery = "SELECT * FROM student";

    try {
        PreparedStatement pst = conn.prepareStatement();
        ResultSet rs = pst.executeQuery();
        Donor donor;

        while(rs.next()) {
            student = new Student(rs.getString("id"),
            rs.getString("gender"));
            studentList.add(student);
        }

    } catch (SQLException ex) {
        Logger.getLogger(Student.class.getName()).log(Level.SEVERE, null, ex);
    }
    return studentList; 
}

创建一个名为showStudent的函数以显示名为id的特定数据值。(下面的代码male,female为复选框值)

    public void showStudent(int index) throws ParseException {
    if(getStudentList().get(index).getGender().equals("male")) {
                male.setSelected(true);
                female.setSelected(false);
                gender = "male";
            }
            else {
                female.setSelected(true);
                male.setSelected(false);
                gender = "female";
            }
    }

将操作设置为jbutton,当从jtextfield获取值ID时,请在复选框中填写特定的性别值。