Saturday, 25 April 2015

ColorSelector in Java

//save as ChangeColor.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class ChangeColor extends JFrame implements AdjustmentListener
{
    JScrollBar red;
    JScrollBar green;
    JScrollBar blue;
    int cr = 0;
    int cg = 0;
    int cb = 0;

    ChangeColor()
    {
        super("SCROLLBAR DEMO");
    
        setLayout(new BorderLayout());
        setVisible(true);
        setSize(300,300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        red = new JScrollBar(JScrollBar.VERTICAL,0,10,0,255);
        red.setBackground(Color.red);

        green = new JScrollBar(JScrollBar.HORIZONTAL,0,10,0,255);
        green.setBackground(Color.green);

        blue = new JScrollBar(JScrollBar.VERTICAL,0,10,0,255);
        blue.setBackground(Color.blue);

        add(red,BorderLayout.WEST);
        add(green,BorderLayout.NORTH);
        add(blue,BorderLayout.EAST);

        red.addAdjustmentListener(this);
        green.addAdjustmentListener(this);
        blue.addAdjustmentListener(this);
    }

    public void adjustmentValueChanged(AdjustmentEvent ae)
    {
        if(ae.getSource()==red)
        {
            cr=ae.getValue();
        }
        else if(ae.getSource()==green)
        {
            cg=ae.getValue();
        }
        else if(ae.getSource()==blue)
        {
            cb=ae.getValue();
        }
        System.out.println(cr + ":" + cg + ":" + cb);

        // add color to content pane
        this.getContentPane().setBackground(new Color(cr,cg,cb));
    }

    public static void main(String soham[])
    {
        ChangeColor obj = new ChangeColor();
    }
}
Output

No comments:

Post a Comment