Search code examples
javaswingjradiobutton

Selecting radio buttons to make text appear


Using radio buttons displayed on a panel, is it possible to select the radio button and then display some text on the panel explaining what the user has selected?

So here is a list of radio buttons

    public void RadioButtons() {
    btLdap = new JRadioButton ("Ldap");
    btLdap.setBounds(60,85,100,20);
    panelHolder.add(btLdap);

    btKerbegos = new JRadioButton ("Kerbegos");
    btKerbegos.setBounds(60,115,100,20);
    panelHolder.add(btKerbegos);

    btSpnego =new JRadioButton("Spnego");
    btSpnego.setBounds(60,145,100,20);
    panelHolder.add(btSpnego);

    btSaml2 = new JRadioButton("Saml2");
    btSaml2.setBounds(60,175,100,20);
    panelHolder.add(btSaml2);
}

User selects btLdap

btLdap.setSelected(true);

Now how do you make the text appear on the panel not a message box


Solution

  • If you want to display a text when a radio button is selected you could use ActionListener.

    final JTextArea textArea = new JTextArea();
    add(textArea);
    
    JRadioButton radioButton = new JRadioButton();
    add(radioButton);
    radioButton.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            textArea.setText("Selected");
        }
    });
    
    JRadioButton radioButton2 = new JRadioButton();
    add(radioButton2);
    radioButton2.addActionListener(new ActionListener()
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            textArea.setText("Selected 2");
        }
    });
    
    radioButton.setSelected(true);
    

    When the first is selected it will change the text of the JTextArea with The first is selected!, same the second radio button but with The second is selected.

    As you said, radioButton.setSelected(true); setSelected is used to select/deselect a radio button.

    In this example i used textArea, but you can use everything which have a method to change the text it contains (an image too!)

    Official DOC, here.


    Anyway, actionPerformed is not called when setSelected is used so i would go to something like a method

    private void updateText(int index)
    {
        String text = null;
    
        switch (index)
        {
            case 0:
                text = "Selected";
                break;
            case 1:
                text = "Selected 2";
                break;
        }
    
        textArea.setText(text);
    }
    

    And then call updateText(0 or 1 etc.) when you want to select setSelected another radio button and update the text too.

    All this is useful, if you want to show a "what happens if you press it" message, but if you just want to change the text of the area with the text of the radio button, just use

    textArea.setText(e.getActionCommand());