Create JRadioButtons ActionListener in java
How to Create JRadioButtons ActionListener in java.
I Have two Calsses Main.Java and other Class MyFrame
My Frame Extends JFrame it behaves it’s like a JFrame it
also Implements ActionListener and Constructor.
So going to create 4 JRadioButtons .Button names (window xp,
windows 7, windows 8.1, windows 10).
So we can actually limit the choice selection only one item.
Create now ButtonGroup and we need add this RadioButton to
this Group.
We can use are ActionPerformed method to detect which Button was selected so with in are ActionPerformed method we can place as Simple if Statement.
package javaFxProject;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
public class MyFrame extends JFrame implements ActionListener
{
JRadioButton winxp;
JRadioButton win7;
JRadioButton win8;
JRadioButton win10;
ImageIcon winxpIcon;
ImageIcon win7Icon;
ImageIcon win8Icon;
ImageIcon win10Icon;
MyFrame()
{
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
winxpIcon = new ImageIcon("winxp.png");
win7Icon = new ImageIcon("win7.png");
win8Icon = new ImageIcon("win8.png");
win10Icon = new ImageIcon("win10.png");
winxp = new JRadioButton("Windows XP");
win7 = new JRadioButton("Windows 7");
win8 = new JRadioButton("Windows 8.1");
win10 = new JRadioButton("Windows 10");
ButtonGroup group = new ButtonGroup();
group.add(winxp);
group.add(win7);
group.add(win8);
group.add(win10);
winxp.addActionListener(this);
win7.addActionListener(this);
win8.addActionListener(this);
win10.addActionListener(this);
winxp.setIcon(winxpIcon);
win7.setIcon(win7Icon);
win8.setIcon(win8Icon);
win10.setIcon(win10Icon);
this.add(winxp);
this.add(win7);
this.add(win8);
this.add(win10);
this.pack();
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==winxp)
{
System.out.println("You Selected Windows XP");
}
else if(e.getSource()==win7)
{
System.out.println("You Selected Windows 7");
}
else if(e.getSource()==win8)
{
System.out.println("You Selected Windows 8.1");
}
else if(e.getSource()==win10)
{
System.out.println("You Selected Windows 10");
}
}
}
Image 1 |
Image 2 |
Comments
Post a Comment