Google+ Radio Buttons In Java Applets[How to] - CodieeHome
“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”
__

Radio Buttons in Java

Goal--  Write a java applet program in which we can select shapes using Radio Buttons and  Enlarge or Shrink them  using buttons.

Explanation:- Explanation is given in program through Comments.

Program:-

/*<applet code=applet width=400 height=400></applet>*/

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class applet extends Applet implements ActionListener,ItemListener

   {

        //Radio Buttons to be Selected.

        Checkbox c1;

        Checkbox c2;

        Checkbox c3;

      //Button to Click

        Button b1;

        Button b2;

        int x,y;

       CheckboxGroup cb;//Necessary to only allow one radio button to be selected at the same time

  public void init()

{  

         x=100;

         y=100;

        cb=new CheckboxGroup();

        setBackground(Color.pink); // Setting Background color

        c1=new Checkbox("Circle",false,cb); //Initializing Radio Buttons.

        c2=new Checkbox("Rectangle",false,cb);

        c3=new Checkbox("Round Rectangle",false,cb);

        b1=new Button("Enlarge"); //Initializing Button and give it a text.

        b2=new Button("Shrink");

        add(c1); // Adding Buttons to Applet.

        add(c2);

        add(c3);

        add(b1);

        add(b2);

       c1.addItemListener(this);

       c2.addItemListener(this);

       c3.addItemListener(this);

       b1.addActionListener(this);

       b2.addActionListener(this);

 }

public void paint(Graphics g)

 {

       if(c1.getState()) //Getting state of C1 radio button

            {

                g.setColor(Color.cyan);

               g.fillOval(150,150,x,y);

            }

if(c2.getState()) //Getting state of C2 radio button

            {

g.setColor(Color.magenta);

                g.fillRect(150,150,x,y);

             }

        if(c3.getState()) //Getting state of C3 radio button

              {

                  g.setColor(Color.orange);

                  g.fillRoundRect(150,150,x,y,15,15);

               }

}

public void actionPerformed(ActionEvent e) //Called just After the user perform Action.

 {

String s=e.getActionCommand();

        if(s.equals("Enlarge"))

{

                x+=10;

                y+=10;

                repaint();

}

      if(s.equals("Shrink"))

{

x-=10;

                y-=10;

                 repaint();

}

 }

public void itemStateChanged(ItemEvent i)  //invoked when state of any item changes.

{

        x=100;

        y=100;

repaint();

 }

 }

Output:-

                

  

 This article is contributed by Shubham Gupta.


If you want to share more information about topic discussed above

or find anything incorrect Please do comments.  

0 comments:

Post a Comment

 
Top