JAVA Program using Applet to Change Color of Text using Choice List

JAVA Program using Applet to Change Color of Text using Choice List:

/*
        This java example shows how to get selected item of a choice or combobox
        using Java AWT Choice class.
*/

import java.applet.Applet;
import java.awt.Color;
import java.awt.Choice;
import java.awt.Graphics;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

/*
<applet code="SelectedColorItem.class"
         width=200
         height=200>
</applet>
*/

public class SelectedColorItem extends Applet implements ItemListener{

        Choice ch = null;

        public void init(){

                //create choice or combobox
                ch = new Choice();

                //add items to the choice
                ch.add("red");
                ch.add("blue");
                ch.add("green");
                ch.add("yellow");

                //add choice or combobox
                add(ch);

                //add item listener
                ch.addItemListener(this);

        }

        public void paint(Graphics g){
                /*
                 * To get selected item, use
                 * String getSelectedItem()
                 * method of AWT Choice class.
                 */
                 setBackground(Color.white);
                 String c = ch.getSelectedItem();
                 if(ch.getSelectedItem()=="red")
                    setForeground(Color.red);
                 if(ch.getSelectedItem()=="blue")
                    setForeground(Color.blue);
                 if(ch.getSelectedItem()=="green")
                    setForeground(Color.green);
                 if(ch.getSelectedItem()=="yellow")
                    setForeground(Color.yellow);

                g.drawString(c,10, 70);
             //   g.drawString(ch.getSelectedItem(),10, 70);
        }

        public void itemStateChanged(ItemEvent arg0) {
                repaint();
        }
}

OUTPUT:

JAVA Program using Applet to Change Color of Text using Choice List

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.