Saturday, 25 April 2015

Adapter class Demo in Java

//save as AdapterDemo.java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class AdapterDemo extends Applet
{
    int x,y;
    public void init()
    {
        addMouseListener(new MyMouseAdapter(this));
    }

    class MyMouseAdapter extends MouseAdapter
    {
        AdapterDemo obj;

        MyMouseAdapter(AdapterDemo obj)
        {
            this.obj = obj;
        }
 
        public void mouseClicked(MouseEvent me)
        {
           obj.showStatus("Mouse Clicked...");
           x = me.getX();
           y = me.getY();
           repaint();
        }
    }

    public void paint(Graphics g)
    {
        g.drawString("Mouse Clicked at: " + x + "," + y,10,10);
    }
}

/*


*/
Output

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