Mark Jhomel Olimon Mark Jhomel Olimon - 5 months ago 44
Java Question

Selecting jButton based on the text retrieved from the Data Base

I have again a problem regarding on using database to a program in netbeans. This is my problem, I have a button group which contains male and female button. When you clicked the 'Submit' button, the selected button will write the text of it to mySQL data base. So the problem is, I don't know the reverse of it.

I will make my question as clear as possible. I want to retrieve a text from database and select that retrieved text in one of the buttons of button group.

For example, I retrieved 'male' from the data base, so I want a code to select 'male' radio button. Thank you.


So I got it now. I am looking for some method that will instantly select a button from a text retrieved in data base. I used the crude process, little messy but it worked nice!

String temp = (jTable1.getModel().getValueAt(row, 11).toString());

if ("Male".equals(temp)) {
else if ("Female".equals(temp)) {


ButtonGroup has a setSelected(...) method that would help you set one of the JRadioButtons that it contains, and set its state. For example in the code below, I use a JComboBox to select one of the JRadioButton texts, and then use the ButtonGroup to activate the selected String:

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;    
import javax.swing.*;

public class SelectButton extends JPanel {
    private static final String[] TEXTS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
    private ButtonGroup buttonGroup = new ButtonGroup();
    private JComboBox<String> comboBox = new JComboBox<>(TEXTS);

    public SelectButton() {
        JPanel rBtnPanel = new JPanel(new GridLayout(1, 0));
        for (String text : TEXTS) {
            JRadioButton radioButton = new JRadioButton(text);

        comboBox.addActionListener(new ComboListener());
        JPanel bottomPanel = new JPanel();

        setLayout(new BorderLayout());
        add(rBtnPanel, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.PAGE_END);

    private class ComboListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String command = comboBox.getSelectedItem().toString();
            Enumeration<AbstractButton> elements = buttonGroup.getElements();
            while (elements.hasMoreElements()) {
                AbstractButton btn = elements.nextElement();
                if (btn.getActionCommand().equals(command)) {
                    buttonGroup.setSelected(btn.getModel(), true);


    private static void createAndShowGui() {
        SelectButton mainPanel = new SelectButton();

        JFrame frame = new JFrame("Main");

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {