Search code examples
javaswingjradiobutton

Set selected JRadioButton using information from database


I'm currently creating a java swing app, where users can create a profile, specifically for this question's purpose, choose their gender. Here is the code:

    rbnMale = new JRadioButton("M");
    rbnMale.setBorderPainted(false);
    rbnMale.setContentAreaFilled(false);
    rbnMale.setFocusPainted(false);
    rbnMale.setOpaque(false);
    rbnMale.setBounds(171, 328, 38, 23);
    add(rbnMale);

    rbnFemale = new JRadioButton("F");
    rbnFemale.setBorderPainted(false);
    rbnFemale.setContentAreaFilled(false);
    rbnFemale.setFocusPainted(false);
    rbnFemale.setOpaque(false);
    rbnFemale.setBounds(218, 328, 38, 23);
    add(rbnFemale);

    ButtonGroup gender = new ButtonGroup();
    gender.add(rbnFemale);
    gender.add(rbnMale);

After the user has made their option, this code is then executed

    String gender = "";
            if (rbnMale.isSelected())
                gender = "Male";
            else
                gender = "Female";

in the actionPerform of my button. Then the user's gender is stored in my database as a varchar. However, I want to retrieve this selected gender in another form where my users will then be able to update their information. I want the default selected button to be the value stored in the database, e.g. if the user is a "Female", I want the default selected button to be F. How would I execute this?

P.S To retrieve the user's gender I will be using

volunteer.getGender();

Thank you!!


Solution

  •     String selectedGender = volunteer.getGender().toString();
        if (selectedGender.equals("Female"))
            radioButtonFemale.setSelected(true);
        else 
            radioButtonMale.setSelected(true);
    

    selectedGender retrieves the gender from the database, then and if else statement is used to check the value of the gender. If "Female" was selected, female is the default selected radiobutton.