JRadioButton(Another Example)

setIcon( ) method possible to change the icon inside a JButton during program execution.

Program

2 fsfed

 

 

 

Program Source

import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JButton;
import javax.swing.ImageIcon;
import java.awt.FlowLayout;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;

class Frame extends JFrame implements ItemListener{
    
    private JButton jb;
    private JRadioButton jr1,jr2,jr3,jr4;
    private ImageIcon icon;
    
    Frame()
    {
        setTitle("Vehicle Selection");
        setLayout(new FlowLayout());
        setRadioButton();
        setSize(700, 200);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    
    private void setRadioButton()
    {
        jr1 = new JRadioButton("Bicycle");
        add(jr1);
        jr2 = new JRadioButton("Bike");
        add(jr2);
        jr3 = new JRadioButton("Car");
        add(jr3);
        jr4 = new JRadioButton("Train");
        add(jr4);
        icon = new ImageIcon("Vehicles.png");
        jb = new JButton(icon);
        add(jb);
    }
    
    private void setAction()
    {
        jr1.addItemListener(this);
        jr2.addItemListener(this);
        jr3.addItemListener(this);
        jr4.addItemListener(this);
    }
    
    public void itemStateChanged(ItemEvent eve)
    {
        if(jr1.isSelected())
        {
            icon = new ImageIcon("Bicycle.png");
            jb.setIcon(icon);
        }
        else if(jr2.isSelected())
        {
            icon = new ImageIcon("Bike.png");
            jb.setIcon(icon);
        }
        else if(jr3.isSelected())
        {
            icon = new ImageIcon("Car.png");
            jb.setIcon(icon);
        }
        else if(jr4.isSelected())
        {
            icon = new ImageIcon("Train.png");
            jb.setIcon(icon);
        }
        else
        {
            icon = new ImageIcon("Vehicles.png");
            jb.setIcon(icon);
        }
    
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        Frame frame = new Frame();
    }
}

Leave a Comment