Search code examples
javaswingjpaneljradiobuttonbuttongroup

Adding JRadioButton to Group


I have some problems with adding JRadioButton to ButtonGroup and then to JPanel, here is some code:

void modelsRadio () throws SQLException {

    JPanel modelsRadioPanel = new JPanel();

    Statement statement = db.setConnection();
    ResultSet rs = statement.executeQuery("SELECT * FROM МОДЕЛИ");
    ButtonGroup modelRadioGroup = new ButtonGroup();

    while (rs.next()) {

        modelsRadioPanel.add(new JRadioButton(rs.getString("НАЗВАНИЕ")));
        //modelRadioGroup.add(new JRadioButton(rs.getString("НАЗВАНИЕ")));
    }

    frame.add(modelsRadioPanel);
}

The idea is to get data from Oracle SQL Table and create radio's and put data to them, so, I can add them to ButtonGroup but can't add to JPanel. Or, if I don't add them to group and add them to JPanel I can't switch between them normally, they(radio buttons) works like a checkboxes.


Solution

  • Hmm, I solve it like this:

    void modelsRadio () throws SQLException {
    
        JPanel modelsRadioPanel = new JPanel();
    
        Statement statement = db.setConnection();
        ResultSet rs = statement.executeQuery("SELECT * FROM МОДЕЛИ");
        ButtonGroup modelRadioGroup = new ButtonGroup();
    
        while (rs.next()) {
    
           JRadioButton jr = new JRadioButton(rs.getString("НАЗВАНИЕ"));
           //modelRadioGroup.add(new JRadioButton(rs.getString("НАЗВАНИЕ")));
           modelRadioGroup.add(jr);
           modelsRadioPanel.add(jr);   
        }
    
        frame.add(modelsRadioPanel);
    }