Tuesday, April 12, 2016

How to use RadioButtons? ( in java GUI)

//In this program, we will make three radio buttons namely Bold, Italic and Normal and make the text in the textField change with the button check.

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class SimpleAnimation extends JFrame{
private JRadioButton button1;
private JRadioButton button2;
private JRadioButton button3;
private JTextField text;
private Font boldFont;
private Font italicFont;
private Font normalFont;
private ButtonGroup group;
//create a constructor 
public SimpleAnimation(){
super("Magic");               //This class is a subclass of JFrame
setLayout(new FlowLayout());
//cretes text field and writes something
text = new JTextField("Are you learning something?.");
//create buttons and add them to the frame
button1 = new JRadioButton("Bold");
button2 = new JRadioButton("Italic");
button3 = new JRadioButton("Normal");
//define font
boldFont = new Font("Serif",Font.BOLD,14);
italicFont = new Font("Serif",Font.ITALIC,14);
normalFont = new Font("Serif",Font.PLAIN,14);
//radio button group
group = new ButtonGroup();
/*add itemListener (Pay attention to ItemListener here)
  * We have created a constructor of the inner class that takes
  *Font object as parameter.Why are we doing so?         */

button1.addItemListener(new ButtonActivity(boldFont));
button2.addItemListener(new ButtonActivity(italicFont));
button3.addItemListener(new ButtonActivity(normalFont));
//Inner class that implements ItemListener
private class ButtonActivity implements ItemListener{
private Font font;
public ButtonActivity(Font f){
font = f;
public void itemStateChanged(ItemEvent e){


//Diver method or main method

import javax.swing.JFrame;
import javax.swing.JPanel;

public class SimpleAnimationTest {
public static void main(String[]args){
SimpleAnimation frame = new SimpleAnimation();
    frame.setSize(600, 200);




Puja sharma said...

It’s an awesome post in support of all the web visitors; they will obtain benefit from it I am sure.Have a look at my website:
Packers And Movers Chikkalasandra bengaluru
Packers And Movers CV Raman Nagar
Packers And Movers Bangalore claim to be the #best packers and movers Bangalore offering premium administrations and fulfilling each client that has benefited our administrations.

Anonymous said...

nice tutorial and simple to understand

Sweta Rathore said...

Packers and Movers Bangalore Will Ensure Tension-Free Move

Ready to move? Request free quotes today!

Packers and Movers Bangalore @ http://www.shiftingguide.in/packers-and-movers-bangalore.html

Sunaya Rana said...

Get reliable shifting service provider in Goa at Dealkare packers and movers.
Packers and Movers in Goa