Showing posts with label Java AWT Codes. Show all posts
Showing posts with label Java AWT Codes. Show all posts

Creating WindowEvent using Applet and AWT

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

class MyFrame extends Frame implements MouseMotionListener
{
   int x,y;
   String msg="";
   public MyFrame(String s)
   {
   super(s);
   setBackground(Color.yellow);
   setForeground(Color.blue);
   setSize(200,200);
   setVisible(true);


   //create an object to handle window events
   MyWindowAdapter adapter=new MyWindowAdapter(this);

   //register it to receive those events
   addWindowListener(adapter);

   //register it to receive its own mouse motion events
   addMouseMotionListener(this);
    }

    public void mouseDragged(MouseEvent me)
    {
        x=me.getX();
        y=me.getY();
        msg="Dragging mouse at ("+x+","+y+")";
        repaint();
    }
    public void mouseMoved(MouseEvent me)
    {
        x=me.getX();
        y=me.getY();
        msg="Moving mouse at ("+x+","+y+")";
        repaint();
    }
    public void paint(Graphics g)
    {
        g.drawString(msg,x,y);

    }
}

class MyWindowAdapter extends WindowAdapter
{
    MyFrame myframe;
    public MyWindowAdapter(MyFrame myframe)
    {
        this.myframe=myframe;
    }
    public void windowClosing(WindowEvent we)
    {
        myframe.setVisible(false);
    }
}

public class WindowEvents extends Applet
{
    Frame f;

    public void init()
    {
         f=new MyFrame("My first frame..");

    }
    public void start()
    {
        f.setVisible(true);
    }
    public void stop()
    {
        f.setVisible(false);
    }

    public void paint(Graphics g)
    {
        g.drawString("This is in applet window",10,50);

    }

}
READ MORE - Creating WindowEvent using Applet and AWT

Creating TextField using Applet and AWT

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class TextField2 extends Applet implements ActionListener {
  /* Declaration */
  TextField Input;
  TextField Echo;

  public TextField2 () {
    /* Instantiation */
    Input = new TextField ("Enter text", 35);
    Echo = new TextField ("Text entered above will appear here.", 35);


    /* Decoration */
    setBackground (Color.yellow);
    Input.setBackground (Color.green);
    Echo.setForeground (Color.blue);

    /* Location */

    add (Input);
    add (Echo);


    /* Configuration */
    Echo.setEditable (false);
    Input.addActionListener (this);
  }

  public void actionPerformed (ActionEvent e) {
    Echo.setText (Input.getText());
  }
}
READ MORE - Creating TextField using Applet and AWT

Creating TextArea using Applet and AWT

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class TextArea2 extends Applet implements  TextListener
{
  /* Declaration */

  private TextArea Echo;
  private TextArea Echo2;


  public TextArea2 () {
    /* Instantiation */
    //Input = new TextField ("Input", 30);
    Echo = new TextArea (5, 30);
    Echo2 = new TextArea (5, 30);


    /* Configuration */

    Echo.addTextListener (this);
    Echo2.setEditable (false);

    /* Location */

    add (Echo);
    add (Echo2);

    /* Decoration */
    setBackground (Color.yellow);
    Echo.setBackground (Color.green);
    Echo.setText ("Enter text in this area");
  }

  public void textValueChanged (TextEvent e)
  {
    String Entry;
    Entry = Echo.getText ();
    Echo2.setText (Entry);
  }

}
READ MORE - Creating TextArea using Applet and AWT

Creating Thread using Applet and AWT

import java.awt.*;
import java.applet.*;
/*
<applet code=SimpleThread width=300 height=100>
<param name=message value=" Computer Programming -2 ">
</applet>
*/
public class SimpleThread extends Applet implements Runnable
{
String msg;
Thread t=null;
int state;
boolean stopflag;

public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
showStatus("now in init() method....." );
}

public void start()
{
t=new Thread(this);
stopflag=false;
msg=getParameter("message");
t.start();
showStatus("now in start() method....." );
}

public void run()
{
char ch;
for( ; ; )
{
try
{
repaint();
Thread.sleep(250);
ch=msg.charAt(0);
msg=msg.substring(1,msg.length());
msg+=ch;
if(stopflag)
break;
}
catch(InterruptedException e)
{
}
}

}

public void paint(Graphics g)
{
g.drawString(msg,50,30);
showStatus("now in paint() method....." );
}

public void stop()
{
stopflag=true;
t=null;
showStatus("now in stop() method....." );
}

public void destroy()
{
showStatus("now in destroy() method....." );
}

}


READ MORE - Creating Thread using Applet and AWT

Creating Scrollbar using Applet and AWT

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Scrollbar2 extends Applet implements AdjustmentListener {
  /* Declaration */

  private Scrollbar HSelector;
  private Scrollbar VSelector;

  private Label Report;

  public Scrollbar2 ()
  {
    /* Instantiation */
    setForeground(Color.blue);
    HSelector = new Scrollbar ();
    VSelector = new Scrollbar (Scrollbar.VERTICAL);

    Report = new Label ();

    /* Decoration */
    HSelector.setMaximum (300);
    HSelector.setOrientation (Scrollbar.HORIZONTAL);
    VSelector.setMaximum (300);
    Report.setAlignment (Label.CENTER);


    /* Location */
    add (Report);
    add (HSelector);
    add (VSelector);

    /* Configuration */
    HSelector.addAdjustmentListener (this);
    VSelector.addAdjustmentListener (this);

    /* Initialization */
    HSelector.setValue (100);
    VSelector.setValue (150);

    Report.setText ("H = " + HSelector.getValue() +
                    ", V = " + VSelector.getValue());
  }

  public void adjustmentValueChanged(AdjustmentEvent e)
  {
    Report.setText ("H = " + HSelector.getValue() +
                    ", V = " + VSelector.getValue());
    repaint();
  }


   public void paint (Graphics g)
   {
    g.drawOval (20,100,HSelector.getValue (), VSelector.getValue ());
   }
}

READ MORE - Creating Scrollbar using Applet and AWT

Rectangle Example using Applet and AWT

import java.awt.*;
import java.applet.*;
/*
<applet CODE="RectExample.class" WIDTH=150 HEIGHT=150>
</applet>
*/
public class RectExample extends Applet
{
   public void paint(Graphics g)
    {
        g.drawRect(10,10,50,50);
        g.fillRect(10,80,50,50);
        g.drawRoundRect(80,10,50,50,30,30);
        g.fillRoundRect(80,80,50,50,30,30);
    }
}
READ MORE - Rectangle Example using Applet and AWT

Polygon Example using Applet and AWT

import java.awt.*;
import java.applet.*;
/*
<applet CODE="PolygonExample.class" WIDTH=400 HEIGHT=150>
</applet>
*/

public class PolygonExample extends Applet
{

    public void paint(Graphics g)
    {
        int xpoints[]={100,300,350,300,300,100,100,50};
        int ypoints[]={10,10,50,50,100,100,50,50};
        int npoints=8;
        g.drawPolygon(xpoints,ypoints,npoints);
        int xpoints1[]={180,220,220,180};
        int ypoints1[]={50,50,100,100};
        int npoints1=4;
        g.fillPolygon(xpoints1,ypoints1,npoints1);

    }
}
READ MORE - Polygon Example using Applet and AWT

getParameter( ) using Applet and AWT

import java.applet.Applet;
import java.awt.*;

/*
<applet CODE="ParamTest.class" WIDTH=400 HEIGHT=100>
<param name=message  value="Testing parameters......">
<param name=fontname value=TimesNewRoman>
<param name=fontsize value=14>
</applet>
*/
public class ParamTest extends Applet
{
String msg,fn;
int fs;

public void init()
{
    setBackground(Color.blue);
    setForeground(Color.white);
}

public void start()
{
    String s;
    msg=getParameter("message");
    fn=getParameter("fontname");
    if(fn==null)
        fn="not found";
    s=getParameter("fontsize");
    try
    {
        if(s!=null)
            fs=Integer.parseInt(s);
        else
            fs=0;
    }
    catch(NumberFormatException e)
    {
        fs=-1;
    }
}

public void paint(Graphics g)
{
    g.drawString(msg,20,20);
    g.drawString("Font name : "+fn,20,40);
    g.drawString("Font size : "+fs,20,60);
    showStatus("Passing parameters to applet");
}
}
READ MORE - getParameter( ) using Applet and AWT

Paint example using Applet and AWT

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="PaintDemo" width=800 height=800>
</applet>*/
public class PaintDemo extends Applet implements ActionListener,MouseListener, MouseMotionListener
{
String msg=" ";
int i,cnt=0,o=1,c=0,mousex=0,mousey=0,s1,s2,e1,e2;
int points[][]=new int [100][6];
Button line,oval,rect,red,green,blue;


public void init()
{
setLayout(null);
line=new Button("Line");
oval=new Button("Oval");
rect=new Button("Rectangle");
red=new Button("Red");
green=new Button("Green");
blue=new Button("Blue");

add(line);
add(oval);
add(rect);
add(red);
add(green);
add(blue);

line.addActionListener(this);
oval.addActionListener(this);
rect.addActionListener(this);
red.addActionListener(this);
green.addActionListener(this);
blue.addActionListener(this);

red.setForeground(Color.red);
green.setForeground(Color.green);
blue.setForeground(Color.blue);

line.setBounds(10,10,80,30);
oval.setBounds(10,40,80,30);
rect.setBounds(10,70,80,30);
red.setBounds(10,100,80,30);
green.setBounds(10,130,80,30);
blue.setBounds(10,160,80,30);

addMouseListener(this);
addMouseMotionListener(this);

}

public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand();
if(str.equals("Line"))
o=1;
else if(str.equals("Oval"))
o=2;
else if(str.equals("Rectangle"))
o=3;
else if(str.equals("Red"))
c=1;
else if(str.equals("Green"))
c=2;
else if(str.equals("Blue"))
c=3;
repaint();
}


public void mouseClicked(MouseEvent me){  }

public void mouseEntered(MouseEvent me){  }

public void mouseExited(MouseEvent me) {  }

public void mousePressed(MouseEvent me)
{
points[cnt][0]=me.getX();
points[cnt][1]=me.getY();
points[cnt][4]=o;
points[cnt][5]=c;
}


public void mouseReleased(MouseEvent me)
{
points[cnt][2]=me.getX();
points[cnt][3]=me.getY();
cnt++;

}


public void mouseDragged(MouseEvent me)
{
points[cnt][2]=me.getX();
points[cnt][3]=me.getY();
repaint();
showStatus("dragging mouse at "+me.getX()+","+me.getY());
}

public void mouseMoved(MouseEvent me) { }

public void paint(Graphics g)
{
int width=0,height=0;
for(i=0;i<=cnt;i++)
{
if(points[i][5]==3)
g.setColor(Color.blue);
else if(points[i][5]==2)
g.setColor(Color.green);
else if (points[i][5]==1)
g.setColor(Color.red);
else
g.setColor(Color.black);

if(points[i][4]==1)
g.drawLine(points[i][0],points[i][1],points[i][2],points[i][3]);
else if(points[i][4]==2)
g.drawOval(points[i][0],points[i][1],points[i][2]-points[i][0],points[i][3]-points[i][1]);
else if(points[i][4]==3)
g.drawRect(points[i][0],points[i][1],points[i][2]-points[i][0],points[i][3]-points[i][1]);
}
}
}
READ MORE - Paint example using Applet and AWT

FrameWindow using Applet and AWT

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class MyFrameWindow extends Frame
{
    int x,y;
    String msg=" ";
    public MyFrameWindow()
    {
          addWindowListener(new MyWindowAdapter());
          addMouseMotionListener(new MyMouseMotionAdapter(this));
    }

    public void paint(Graphics g)
    {
        msg="Dragging mouse at ("+x+","+y+")";
        g.drawString(msg,x,y);

    }
    public static void main(String  args[])
    {
        MyFrameWindow mf=new MyFrameWindow();
        mf.setTitle("Frame window");
        mf.setSize(new Dimension(200,200));
        mf.setVisible(true);
    }
}


class MyWindowAdapter extends WindowAdapter
{
    public void windowClosing(WindowEvent we)
    {
        System.exit(0);
    }
}

class MyMouseMotionAdapter extends MouseMotionAdapter
{
    MyFrameWindow  myframe;
    public MyMouseMotionAdapter(MyFrameWindow myframe)
    {
            this.myframe=myframe;
    }
    public void mouseDragged(MouseEvent me)
    {
        myframe.x=me.getX();
        myframe.y=me.getY();
        myframe.repaint();
    }
}

READ MORE - FrameWindow using Applet and AWT

Creating Frame using Applet and AWT

import java.awt.*;
import java.applet.*;

class TestFrame extends Frame{
         public TestFrame(String s)
         {
                  super(s);
                  setBackground(Color.cyan);
                  setSize(250,100);
                  setVisible(true);
                     Graphics g = this.getGraphics();
                     g.drawString("Hi! I am  Frame ",50,50);
         }
}

class MyFrameApp {
         public static void main(String[] args) {
                  new TestFrame("Frame demo");
         }
}
READ MORE - Creating Frame using Applet and AWT

MouseAdapter using Applet and AWT

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterDemo extends Applet {

  public void init() {
    setBackground(Color.green);
    addMouseListener(new MyMouseAdapter(this));
  }
}

class MyMouseAdapter extends MouseAdapter
{
  MouseAdapterDemo mad;

  public MyMouseAdapter(MouseAdapterDemo mad) {
    this.mad = mad;
  }

  public void mousePressed(MouseEvent me) {
    mad.setBackground(Color.red);
    mad.repaint();
  }

  public void mouseReleased(MouseEvent me) {
    mad.setBackground(Color.green);
    mad.repaint();
  }
}
READ MORE - MouseAdapter using Applet and AWT

Mouse Events using Applet and AWT

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Mouse2 extends Applet
   implements MouseListener, MouseMotionListener {

   int width, height;
   int x, y;    // the coordinates of the upper-left corner of the box
   int mx, my;  // the most recently recorded mouse coordinates
   boolean isMouseDraggingBox = false;

   public void init() {
      width = getSize().width;
      height = getSize().height;
      //setBackground( Color.black );

      x = width/2 - 20;
      y = height/2 - 20;

      addMouseListener( this );
      addMouseMotionListener( this );
   }

   public void mouseEntered( MouseEvent e ) { }
   public void mouseExited( MouseEvent e ) { }
   public void mouseClicked( MouseEvent e ) { }
   public void mousePressed( MouseEvent e ) {
      mx = e.getX();
      my = e.getY();
      if ( x < mx && mx < x+40 && y < my && my < y+40 ) {
         isMouseDraggingBox = true;
      }
      e.consume();
   }
   public void mouseReleased( MouseEvent e ) {
      isMouseDraggingBox = false;
      e.consume();
   }
   public void mouseMoved( MouseEvent e ) { }
   public void mouseDragged( MouseEvent e ) {
      if ( isMouseDraggingBox ) {
         // get the latest mouse position
         int new_mx = e.getX();
         int new_my = e.getY();

         // displace the box by the distance the mouse moved since the last event
         // Note that "x += ...;" is just shorthand for "x = x + ...;"
         x += new_mx - mx;
         y += new_my - my;

         // update our data
         mx = new_mx;
         my = new_my;

         repaint();
         e.consume();
      }
   }

   public void paint( Graphics g ) {
      g.setColor( Color.red );
      g.fillRect( x, y, 40, 40 );
   }
}
READ MORE - Mouse Events using Applet and AWT

Creating Menu using Applet and AWT

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.datatransfer.*;
import java.io.*;
/*<applet code="Menu1" width=400 height=400>
</applet>*/

class MenuFrame extends Frame
{
String msg=" ";
CheckboxMenuItem i13,i14;
TextArea text;


MenuFrame(String title)
{
super(title);
MenuBar mbar=new MenuBar();

text=new TextArea(400,200);
add(text);
text.setEditable(true);
Menu file=new Menu("File");
MenuItem i1,i2,i3,i4,i5;
file.add(i1=new MenuItem("New..."));
file.add(i2=new MenuItem("Open..."));
file.add(i3=new MenuItem("Save..."));
file.add(i4=new MenuItem("-"));
file.add(i5=new MenuItem("Quit..."));
mbar.add(file);

Menu edit=new Menu("Edit");
MenuItem i6,i7,i8,i9,sep;
edit.add(i6=new MenuItem("Cut"));
edit.add(i7=new MenuItem("Copy"));
edit.add(i8=new MenuItem("Paste"));
edit.add(i9=new MenuItem("-"));
Menu sub=new Menu("Align");

MenuItem i10,i11,i12;
sub.add(i10=new MenuItem("Left"));
sub.add(i11=new MenuItem("Right"));
sub.add(i12=new MenuItem("Center"));
edit.add(sub);
edit.add(sep=new MenuItem("-"));

i13=new CheckboxMenuItem("VerticalScrollBar");
edit.add(i13);
i14=new CheckboxMenuItem("HorizontalScrollBar");
edit.add(i14);
mbar.add(edit);

Mymenuhandler handler=new Mymenuhandler(this);
i1.addActionListener(handler);
i2.addActionListener(handler);
i3.addActionListener(handler);
i4.addActionListener(handler);
i5.addActionListener(handler);
i6.addActionListener(handler);
i7.addActionListener(handler);
i8.addActionListener(handler);
i9.addActionListener(handler);
i10.addActionListener(handler);
i11.addActionListener(handler);
i12.addActionListener(handler);
i13.addItemListener(handler);
i14.addItemListener(handler);

MyWindowAdapter adapter=new MyWindowAdapter(this);

addWindowListener(adapter);
setMenuBar(mbar);

}

public void paint(Graphics g)
{
}
}

class MyWindowAdapter extends WindowAdapter
{
MenuFrame menuframe;
public MyWindowAdapter(MenuFrame menuframe)
{
this.menuframe=menuframe;
}

public void windowClosing(WindowEvent we)
{
menuframe.setVisible(false);
}

}





class Mymenuhandler implements ActionListener,ItemListener
{
MenuFrame menuframe;
FileDialog fd;
String pm="you selected : ",msg=" ";
String filename;
public Mymenuhandler(MenuFrame menuframe)
{
this.menuframe=menuframe;
}

public void actionPerformed(ActionEvent ae)
{
String arg=(String)ae.getActionCommand();
if(arg.equals("New..."))
msg=pm+"new";
else if(arg.equals("Open..."))
msg=pm+"Open";
else if(arg.equals("Save..."))
msg=pm+"save";
else if(arg.equals("Quit..."))
msg=pm+"quit";
else if(arg.equals("Edit"))
msg=pm+"Edit";
else if(arg.equals("Cut"))
msg=pm+"Cut";
else if(arg.equals("Copy"))
msg=pm+"Copy";
else if(arg.equals("Paste"))
msg=pm+"Paste";
else if(arg.equals("Left"))
msg=pm+"Left";
else if(arg.equals("Right"))
msg=pm+"Right";
else if(arg.equals("Center"))
msg=pm+"Center";
else if(arg.equals("VerticalScrollBar"))
msg=pm+"Vertical Scroll Bar";
else if(arg.equals("HorizontalScrollBar"))
msg=pm+"Horizontal Scroll Bar";

menuframe.text.setText(msg);
menuframe.repaint();
}

public void itemStateChanged(ItemEvent ie)
{
menuframe.repaint();
}
}

public class Menu1 extends Applet
{
Frame f;

public void init()
{
f=new MenuFrame("Menu demo");
int width=Integer.parseInt(getParameter("width"));
int height=Integer.parseInt(getParameter("height"));
setSize(new Dimension(width,height));
f.setSize(width,height);
f.setVisible(true);
}

public void start()
{
f.setVisible(true);
}

public void stop()
{
f.setVisible(false);
}
}
READ MORE - Creating Menu using Applet and AWT

Creating List using Applet and AWT

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class List2 extends Applet implements ItemListener {
  /* Declaration */

  private List Selector;
  private Font SansSerif;

  public List2 () {
    /* Declaration */
    String [] ColorList;
    int i;

    /* Instantiation */
    ColorList = new String [9];
    SansSerif = new Font ("SansSerif", Font.BOLD, 14);

    Selector = new List ();

    /* Decoration */
    ColorList [0] = "Red";
    ColorList [1] = "Magenta";
    ColorList [2] = "Blue";
    ColorList [3] = "Cyan";
    ColorList [4] = "Green";
    ColorList [5] = "Yellow";
    ColorList [6] = "White";
    ColorList [7] = "Gray";
    ColorList [8] = "Black";
    for (i = 0; i < ColorList.length; ++i) {
      Selector.add (ColorList [i]);
    }
    Selector.setBackground (Color.yellow);
    Selector.setForeground (Color.red);
    Selector.setFont (SansSerif);

    /* Location */

    add (Selector);

    /* Configuration */
    Selector.addItemListener (this);

    /* Initialization */
    Selector.select (5);
    setBackground (Color.yellow);
  }

  public void itemStateChanged(ItemEvent e) {
    int Selection;
    Selection = Selector.getSelectedIndex();
    if (Selection == 0)
    {
      setBackground (Color.red);
    } else if (Selection == 1) {
      setBackground (Color.magenta);
    } else if (Selection == 2) {
      setBackground (Color.blue);
    } else if (Selection == 3) {
      setBackground (Color.cyan);
    } else if (Selection == 4) {
      setBackground (Color.green);
    } else if (Selection == 5) {
      setBackground (Color.yellow);
    } else if (Selection == 6) {
      setBackground (Color.white);
    } else if (Selection == 7) {
      setBackground (Color.gray);
    } else if (Selection == 8) {
      setBackground (Color.black);
    }
  }

}
READ MORE - Creating List using Applet and AWT

Line Example using Applet and AWT

import java.awt.*;
import java.applet.*;
/*
<applet CODE="LineExample.class" WIDTH=150 HEIGHT=150>
</applet>
*/

public class LineExample extends Applet
{

    public void paint(Graphics g)
    {

        // Get the width and height of the Applet
        int width = this.getSize().width;
        int height = this.getSize().height;
        // Fan 20 lines from the bottom-middle, across the top
        for (int counter=0; counter<=width; counter+=(width/20))
            g.drawLine(width/2, height, counter, 0);
    }
}
READ MORE - Line Example using Applet and AWT

Label example using Applet and AWT

import java.applet.*;
import java.awt.*;
import java.awt.event.*;


public class Label2 extends Applet {
  /* Declaration */

  private Label Label1;
  private Label Label2;
  private Label Label3;
  private Label Label4;
  private Label Label5;
  private Label Label6;
  private Label Label7;

  public Label2 () {

    /* Instantiation */


    Label1 = new Label ("A Label with yellow background");
    Label2 = new Label ("A Label with Blue text");
    Label3 = new Label ();

    /* Location */

    add (Label1);
    add (Label2);
    add (Label3);


    /* Decoration */
    Label1.setBackground (Color.yellow);
    Label2.setForeground (Color.blue);
    Label3.setText ("Text added with setText");
  }

}
READ MORE - Label example using Applet and AWT

KeyEvents using Applet and AWT

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*
<applet code="KeyEvents" width=300 height=100>
</applet>
*/

public class KeyEvents extends Applet implements KeyListener
{
String msg=" ";

public void init()
{
addKeyListener(this);
requestFocus();
}
public void keyPressed(KeyEvent ke)
{
showStatus("key down");
int key=ke.getKeyCode();
switch(key)
{
case KeyEvent.VK_F1: msg+="<f1>";
                    break;
case KeyEvent.VK_F2: msg+="<f2>";
                    break;
case KeyEvent.VK_F3: msg+="<f3>";
                    break;
case KeyEvent.VK_PAGE_DOWN: msg+="<page down>";
                            break;
case KeyEvent.VK_PAGE_UP: msg+="<page up>";
                            break;
case KeyEvent.VK_LEFT: msg+="<left arrow>";
                            break;
case KeyEvent.VK_RIGHT: msg+="<right arrow>";
                            break;
case KeyEvent.VK_ENTER: msg+="<Enter>";
                            break;
case KeyEvent.VK_ESCAPE: msg+="<Escape>";
                            break;
case KeyEvent.VK_SHIFT: msg+="<Shift>";
                            break;
case KeyEvent.VK_ALT: msg+="<Alt>";
                            break;
case KeyEvent.VK_CONTROL: msg+="<Control>";
                            break;
case KeyEvent.VK_CANCEL: msg+="<Cancel>";
                            break;
case KeyEvent.VK_UP: msg+="<Up>";
                            break;
case KeyEvent.VK_DOWN: msg+="<Down>";
                            break;

}
repaint();
}


public void keyReleased(KeyEvent ke)
{
showStatus("Key Up");
}

public void keyTyped(KeyEvent ke)
{
msg+=ke.getKeyChar();
repaint();
}

public void paint(Graphics g)
{
g.drawString(msg,10,20);
}
}


READ MORE - KeyEvents using Applet and AWT

Creating Mouse Events using Applet and AWT

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;

public class Keyboard2 extends Applet
   implements KeyListener, MouseListener, MouseMotionListener
   {

   int width, height;
   int N = 25;
   Color[] spectrum;
   Vector listOfPositions;
   String s = "";
   int skip = 0;

   public void init()
   {
      width = getSize().width;
      height = getSize().height;
      //setBackground( Color.black );

      spectrum = new Color[ N ];
      for ( int i = 0; i < N; ++i )
      {
         spectrum[i] = new Color( Color.HSBtoRGB(i/(float)N,1,1) );
      }

      listOfPositions = new Vector();

      addKeyListener( this );
      addMouseListener( this );
      addMouseMotionListener( this );
   }

   public void keyPressed( KeyEvent e ) { }
   public void keyReleased( KeyEvent e ) { }

   public void keyTyped( KeyEvent e )
   {
      char c = e.getKeyChar();
      if ( c != KeyEvent.CHAR_UNDEFINED )
      {
         s = s + c;
         repaint();
         e.consume();
      }
   }

   public void mouseEntered( MouseEvent e ) { }
   public void mouseExited( MouseEvent e ) { }

   public void mouseClicked( MouseEvent e )
   {
      s = "";
      repaint();
      e.consume();
   }

   public void mousePressed( MouseEvent e ) { }
   public void mouseReleased( MouseEvent e ) { }
   public void mouseMoved( MouseEvent e )
   {

      // only process every 5th mouse event
      if ( skip > 0 ) {
         -- skip;  // this is shorthand for "skip = skip-1;"
         return;
      }
      else skip =5;

      if ( listOfPositions.size() >= N )
      {
         // delete the first element in the list
         listOfPositions.removeElementAt( 0 );
      }

      // add the new position to the end of the list
      listOfPositions.addElement( new Point( e.getX(), e.getY() ) );

      repaint();
      e.consume();
   }
   public void mouseDragged( MouseEvent e ) { }

   public void paint( Graphics g )
   {
      if ( s != "" ) {
         for ( int j = 0; j < listOfPositions.size(); ++j )
         {
            g.setColor( spectrum[ j ] );
            Point p = (Point)(listOfPositions.elementAt(j));
            g.drawString( s, p.x, p.y );
         }
      }
   }
}

//Click, type, and move the mouse. You might see some flickering. Depending on the speed of your computer, you might also find that the mouse position is being sampled too quickly or too slowly. The upcoming lessons will give you tools to fix both of these problems.
READ MORE - Creating Mouse Events using Applet and AWT

Creating Keyboard events using Applet and AWT

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Keyboard1 extends Applet
   implements KeyListener, MouseListener {

   int width, height;
   int x, y;
   String s = "";

   public void init() {
      width = getSize().width;
      height = getSize().height;
      Font f = new Font ("Courier New", Font.BOLD | Font.ITALIC, 25);
      setFont(f);
      x = width/2;
      y = height/2;

      addKeyListener( this );
      addMouseListener( this );
   }

   public void keyPressed( KeyEvent e ) { }
   public void keyReleased( KeyEvent e ) { }

   public void keyTyped( KeyEvent e ) {
      char c = e.getKeyChar();
      if ( c != KeyEvent.CHAR_UNDEFINED ) {
         s = s + c;
         repaint();
         e.consume();
      }
   }

   public void mouseEntered( MouseEvent e ) { }
   public void mouseExited( MouseEvent e ) { }
   public void mousePressed( MouseEvent e ) { }
   public void mouseReleased( MouseEvent e ) { }

   public void mouseClicked( MouseEvent e ) {
      x = e.getX();
      y = e.getY();
      s = "";
      repaint();
      e.consume();
   }

   public void paint( Graphics g )
   {
      g.drawLine( x, y, x, y-10 );
      g.drawLine( x, y, x+10, y );
      g.setColor( Color.blue );
      g.drawString( s, x, y );
   }
}


/*Try clicking and typing into the applet. You'll probably have to
click at least once before you begin typing, to give the applet the keyboard focus.*/
READ MORE - Creating Keyboard events using Applet and AWT

 
 
 
 


Copyright © 2012 http://codeprecisely.blogspot.com. All rights reserved |Term of Use and Policies|