Sunday, December 14, 2008

AWT(Dialogbox)

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

class MyDialog extends Dialog implements ActionListener{

MyDialog(Frame parent,String msg){

super(parent,"Message");

setSize(200,100);

setLayout(new FlowLayout());
setLocation(400,400);
Label l=new Label(msg);
Button b=new Button("Ok");
add(l);
add(b);
b.addActionListener(this);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dispose();
new DialogboxDemo().setVisible(true);
}
});
setVisible(true);
}
public void actionPerformed(ActionEvent e){
dispose();
new DialogboxDemo().setVisible(true);
}
}

public class DialogboxDemo extends Frame implements ActionListener{

TextField tf;
Label l;
Button b1,b2;

DialogboxDemo(){

super("Send Message");
setSize(400,200);

setLayout(new FlowLayout());

setLocation(200,200);
l=new Label("Enter Message");
add(l);
tf=new TextField(25);
add(tf);
b1=new Button("Enter");
b2=new Button("Exit");

add(b1);
add(b2);

b1.addActionListener(this);
b2.addActionListener(this);

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

setVisible(true);
}

public static void main(String ar[]){
DialogboxDemo d=new DialogboxDemo();
}
public void actionPerformed(ActionEvent e){
if(e.getActionCommand()=="Enter")
{
dispose();
new MyDialog(this,tf.getText());
}
else
System.exit(1);
}
}

AWT(ScrollBar)

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

public class ScrollDemo extends Frame implements AdjustmentListener,WindowListener{

Scrollbar r,g,b;


ScrollDemo(){

super("Scroll Color Setting");
setSize(500,600);

setLayout(new FlowLayout());

r=new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,255);
g=new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,255);
b=new Scrollbar(Scrollbar.HORIZONTAL,0,1,0,255);
add(r);
add(g);
add(b);



setVisible(true);



r.addAdjustmentListener(this);
g.addAdjustmentListener(this);
b.addAdjustmentListener(this);

addWindowListener(this);

Color c=new Color(r.getValue(),g.getValue(),b.getValue());
setBackground(c);
}


public void windowActivated(WindowEvent e){}

public void windowClosed(WindowEvent e){}

public void windowClosing(WindowEvent e){
System.exit(0);
}

public void windowDeactivated(WindowEvent e){}

public void windowDeiconified(WindowEvent e){}

public void windowIconified(WindowEvent e){}

public void windowOpened(WindowEvent e){}



public void adjustmentValueChanged(AdjustmentEvent e){

Color c=new Color(r.getValue(),g.getValue(),b.getValue());
setBackground(c);
}

public static void main(String ar[]){
ScrollDemo cH=new ScrollDemo();


}
}

AWT(Label)

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

public class Mlabel extends Frame implements MouseMotionListener,WindowListener {

Label x1=new Label("X=");
Label x2=new Label(" ");
Label y1=new Label("Y=");
Label y2=new Label(" ");

Mlabel(){
super("Mouse Movent");
setSize(300,300);
setLayout(new FlowLayout());

add(x1);
add(x2);
add(y1);
add(y2);




addMouseMotionListener(this);
addWindowListener(this);
setVisible(true);

}


public void windowActivated(WindowEvent e){}

public void windowClosed(WindowEvent e){}

public void windowClosing(WindowEvent e){
System.exit(0);
}

public void windowDeactivated(WindowEvent e){}

public void windowDeiconified(WindowEvent e){}

public void windowIconified(WindowEvent e){}

public void windowOpened(WindowEvent e){}

public void mouseMoved(MouseEvent e){
int x=e.getX();
int y=e.getY();
String t1=" "+x;
String t2=" "+y;

x2.setText(t1);
y2.setText(t2);
}

public void mouseDragged(MouseEvent e){
int x=e.getX();
int y=e.getY();
String t1=" "+x;
String t2=" "+y;

x2.setText(t1);
y2.setText(t2);
}

public static void main(String[] ar){
Mlabel m=new Mlabel();
}
}

AWT(Choice)

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

public class ChoiceDemo extends Frame implements ItemListener,WindowListener{

Choice os;

Label L;


ChoiceDemo(){

super("Choice Selection");
setSize(400,500);

setLayout(new FlowLayout());

os=new Choice();
L=new Label(" ");

os.add("Canada");
os.add("America");
os.add("United Kindom");
os.add("Australia");
os.add("Pakistan");

add(os);
add(L);

setVisible(true);



os.addItemListener(this);
addWindowListener(this);
}

public void windowActivated(WindowEvent e){}

public void windowClosed(WindowEvent e){}

public void windowClosing(WindowEvent e){
System.exit(0);
}

public void windowDeactivated(WindowEvent e){}

public void windowDeiconified(WindowEvent e){}

public void windowIconified(WindowEvent e){}

public void windowOpened(WindowEvent e){}

public void itemStateChanged(ItemEvent e){

L.setText(os.getSelectedItem());
}

public static void main(String ar[]){
ChoiceDemo cH=new ChoiceDemo();


}
}

AWT(Checkbox)

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

public class CheckboxDemo extends Frame implements ItemListener,WindowListener {

CheckboxGroup cbg=new CheckboxGroup();

Checkbox c1=new Checkbox("RED",cbg,false);
Checkbox c2=new Checkbox("GREEN",cbg,false);
Checkbox c3=new Checkbox("BLUE",cbg,false);
Checkbox c4=new Checkbox("YELLOW",cbg,false);
Checkbox c5=new Checkbox("BLACK",cbg,false);

CheckboxDemo(){
super("CheckBox Selection");
setSize(400,500);



setLayout(new FlowLayout());




add(c1);
add(c2);
add(c3);
add(c4);
add(c5);




c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
c4.addItemListener(this);
c5.addItemListener(this);

addWindowListener(this);

setVisible(true);

}


public void windowActivated(WindowEvent e){}

public void windowClosed(WindowEvent e){}

public void windowClosing(WindowEvent e){
System.exit(0);
}

public void windowDeactivated(WindowEvent e){}

public void windowDeiconified(WindowEvent e){}

public void windowIconified(WindowEvent e){}

public void windowOpened(WindowEvent e){}





public void itemStateChanged(ItemEvent e){



if(c1.getState()==true)
{
this.setBackground(Color.red);
}
else
if(c2.getState())
{
setBackground(Color.green);
}
else
if(c3.getState())
{
setBackground(Color.blue);
}
else
if(c4.getState())
{
setBackground(Color.yellow);
}
else
if(c5.getState())
{
setBackground(Color.black);
}
}


public static void main(String[] ar){
CheckboxDemo m=new CheckboxDemo();
}
}

AWT(User Login Using Frame)

import java.awt.*;
import java.awt.event.*;
import java.lang.*;

public class ULogin extends Frame
{
Frame f1;
Frame f2;
Label lb[];
Button buts[];
TextField txt[];
String val1 = "";
String val2 = "";

public ULogin()
{
int top = 85;
f1 = new Frame();
f2 = new Frame();
buts= new Button[5];
lb = new Label[6];
txt = new TextField[5];
int k = 0;
ButtonHandler1 ref1 = new ButtonHandler1();
ButtonHandler2 ref2 = new ButtonHandler2();
ButtonHandler3 ref3 = new ButtonHandler3();
lb[0] = new Label("ID");
lb[1] = new Label("PASSWORD");
lb[2] = new Label("ENTER ID");
lb[3] = new Label("ENTER PASSWORD");
lb[4] = new Label("AUTHORIZATION STATUS");
lb[5] = new Label("PLEASE ENTER THE NECESSARY DETAILS , SHOWN IN BLUE COLOUR");
lb[5].setForeground(Color.red);
for( int i=0;i<5;i++){
lb[i].setBounds(50,top,150,35);
lb[i].setForeground(Color.blue);
k++;
top = top + 55;
if(k == 2)
top = 85;
}
top = 85;
k = 0;
for( int i=0;i<5;i++){
txt[i] = new TextField(20);
txt[i].setBounds(280,top,250,35);
k++;
top = top + 55;
if(k == 2)
top = 85;
}
txt[3].setEchoChar('*');
lb[5].setBounds(50,30,350,30);
for( int i=0;i<4;i++){
if(i%2==0){
buts[i] = new Button("OK");
buts[i].setForeground(Color.red);
buts[i].setBounds(90,280,170,55);
}else{
buts[i] = new Button("CANCEL");
buts[i].setForeground(Color.red);
buts[i].setBounds(315,280,170,55);
}
buts[i].addActionListener(ref1);
}

buts[4]= new Button("BACK");
buts[4].setForeground(Color.red);
buts[4].setBounds(540,280,150,55);
buts[4].addActionListener(ref3);

buts[2].addActionListener(ref2);
f1.add(lb[0]);
f1.add(lb[1]);
f1.add(txt[0]);
f1.add(txt[1]);
f1.add(buts[0]);
f1.add(buts[1]);
f2.add(lb[2]);
f2.add(lb[3]);
f2.add(lb[4]);
f2.add(txt[2]);
f2.add(txt[3]);
f2.add(txt[4]);
f2.add(buts[2]);
f2.add(buts[3]);
f2.add(buts[4]);
f1.setTitle("CREATE ID");
f2.setTitle("USER LOGIN ACCESS");
f1.setBounds(25,125, 575,355);
f2.setBounds(125,125, 775,355);
f1.setLayout(null);
f2.setLayout(null);
f1.setResizable(false);
f2.setResizable(false);
f1.setVisible(true);
f1.addWindowListener(new WindowHandler());
f2.addWindowListener(new WindowHandler());

}

class ButtonHandler1 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
val1 = txt[0].getText();
val2 = txt[1].getText();
if(ae.getActionCommand().equals("OK"))
{
lb[5].setText("PLEASE ENTER THE NECESSARY DETAILS , SHOWN IN BLUE COLOUR");
if(txt[0].getText().equals("")){
f1.add(lb[5]);
}else if(txt[1].getText().equals("")){
f1.add(lb[5]);
}else {
f1.setVisible(false);
f2.setVisible(true);
}
}
if(ae.getActionCommand().equals("CANCEL"))
{
System.exit(0);
}

}
}

class ButtonHandler2 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{

String val3 = txt[2].getText();
String val4 = txt[3].getText();
if(ae.getActionCommand().equals("OK"))
{
if(val1.equals(val3) && val2.equals(val4)){
txt[4].setText("AUTHORIZATION ACCEPTED");
}
else
txt[4].setText("UNAUTHORIZED ACCESS !?! ");
}
}
}



class ButtonHandler3 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{

if(ae.getActionCommand().equals("BACK"))
{
f2.setVisible(false);
f1.setVisible(true);
txt[0].setText("");
txt[1].setText("");
lb[5].setText("");
}
}
}

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

public static void main(String args[])
{
new ULogin();
}
}

AWT(User Login Using Frame)

import java.awt.*;
import java.awt.event.*;
import java.lang.*;

public class ULogin extends Frame
{
Frame f1;
Frame f2;
Label lb[];
Button buts[];
TextField txt[];
String val1 = "";
String val2 = "";

public ULogin()
{
int top = 85;
f1 = new Frame();
f2 = new Frame();
buts= new Button[5];
lb = new Label[6];
txt = new TextField[5];
int k = 0;
ButtonHandler1 ref1 = new ButtonHandler1();
ButtonHandler2 ref2 = new ButtonHandler2();
ButtonHandler3 ref3 = new ButtonHandler3();
lb[0] = new Label("ID");
lb[1] = new Label("PASSWORD");
lb[2] = new Label("ENTER ID");
lb[3] = new Label("ENTER PASSWORD");
lb[4] = new Label("AUTHORIZATION STATUS");
lb[5] = new Label("PLEASE ENTER THE NECESSARY DETAILS , SHOWN IN BLUE COLOUR");
lb[5].setForeground(Color.red);
for( int i=0;i<5;i++){
lb[i].setBounds(50,top,150,35);
lb[i].setForeground(Color.blue);
k++;
top = top + 55;
if(k == 2)
top = 85;
}
top = 85;
k = 0;
for( int i=0;i<5;i++){
txt[i] = new TextField(20);
txt[i].setBounds(280,top,250,35);
k++;
top = top + 55;
if(k == 2)
top = 85;
}
txt[3].setEchoChar('*');
lb[5].setBounds(50,30,350,30);
for( int i=0;i<4;i++){
if(i%2==0){
buts[i] = new Button("OK");
buts[i].setForeground(Color.red);
buts[i].setBounds(90,280,170,55);
}else{
buts[i] = new Button("CANCEL");
buts[i].setForeground(Color.red);
buts[i].setBounds(315,280,170,55);
}
buts[i].addActionListener(ref1);
}

buts[4]= new Button("BACK");
buts[4].setForeground(Color.red);
buts[4].setBounds(540,280,150,55);
buts[4].addActionListener(ref3);

buts[2].addActionListener(ref2);
f1.add(lb[0]);
f1.add(lb[1]);
f1.add(txt[0]);
f1.add(txt[1]);
f1.add(buts[0]);
f1.add(buts[1]);
f2.add(lb[2]);
f2.add(lb[3]);
f2.add(lb[4]);
f2.add(txt[2]);
f2.add(txt[3]);
f2.add(txt[4]);
f2.add(buts[2]);
f2.add(buts[3]);
f2.add(buts[4]);
f1.setTitle("CREATE ID");
f2.setTitle("USER LOGIN ACCESS");
f1.setBounds(25,125, 575,355);
f2.setBounds(125,125, 775,355);
f1.setLayout(null);
f2.setLayout(null);
f1.setResizable(false);
f2.setResizable(false);
f1.setVisible(true);
f1.addWindowListener(new WindowHandler());
f2.addWindowListener(new WindowHandler());

}

class ButtonHandler1 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
val1 = txt[0].getText();
val2 = txt[1].getText();
if(ae.getActionCommand().equals("OK"))
{
lb[5].setText("PLEASE ENTER THE NECESSARY DETAILS , SHOWN IN BLUE COLOUR");
if(txt[0].getText().equals("")){
f1.add(lb[5]);
}else if(txt[1].getText().equals("")){
f1.add(lb[5]);
}else {
f1.setVisible(false);
f2.setVisible(true);
}
}
if(ae.getActionCommand().equals("CANCEL"))
{
System.exit(0);
}

}
}

class ButtonHandler2 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{

String val3 = txt[2].getText();
String val4 = txt[3].getText();
if(ae.getActionCommand().equals("OK"))
{
if(val1.equals(val3) && val2.equals(val4)){
txt[4].setText("AUTHORIZATION ACCEPTED");
}
else
txt[4].setText("UNAUTHORIZED ACCESS !?! ");
}
}
}



class ButtonHandler3 implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{

if(ae.getActionCommand().equals("BACK"))
{
f2.setVisible(false);
f1.setVisible(true);
txt[0].setText("");
txt[1].setText("");
lb[5].setText("");
}
}
}

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

public static void main(String args[])
{
new ULogin();
}
}

AWT(Example For CardLayout)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class CardDeck extends JFrame implements ActionListener
{
private CardLayout cardManager;
private JPanel deck;
private JButton controls[];
private String names[] = { "First card", "Next card", "Previous card", "Last card" };

public CardDeck()
{
super( "CardLayout " );

Container c = getContentPane();

// create the JPanel with CardLayout
deck = new JPanel();
cardManager = new CardLayout();
deck.setLayout( cardManager );

// set up card1 and add it to JPanel deck
JLabel label1 = new JLabel( "card one", SwingConstants.CENTER );
JPanel card1 = new JPanel();
card1.add( label1 );
deck.add( card1, label1.getText() ); // add card to deck

// set up card2 and add it to JPanel deck
JLabel label2 = new JLabel( "card two", SwingConstants.CENTER );
JPanel card2 = new JPanel();

card2.setBackground( Color.yellow );
card2.add( label2 );
deck.add( card2, label2.getText() ); // add card to deck

// set up card3 and add it to JPanel deck
JLabel label3 = new JLabel( "card three" );
JPanel card3 = new JPanel();
card3.setLayout( new BorderLayout() );
card3.add( new JButton( "North" ), BorderLayout.NORTH );
card3.add( new JButton( "West" ), BorderLayout.WEST );
card3.add( new JButton( "East" ), BorderLayout.EAST );
card3.add( new JButton( "South" ), BorderLayout.SOUTH );
card3.add( label3, BorderLayout.CENTER );

deck.add( card3, label3.getText() ); // add card to deck

// create and layout buttons that will control deck
JPanel buttons = new JPanel();
buttons.setLayout( new GridLayout( 2, 2 ) );
controls = new JButton[ names.length ];

for ( int i = 0; i < controls.length; i++ )
{
controls[ i ] = new JButton( names[ i ] );
controls[ i ].addActionListener( this );
buttons.add( controls[ i ] );
}

// add JPanel deck and JPanel buttons to the applet
c.add( buttons, BorderLayout.WEST );
c.add( deck, BorderLayout.EAST );

setSize( 450, 200 );
show();
}

public void actionPerformed( ActionEvent e )
{
if ( e.getSource() == controls[ 0 ] )
cardManager.first( deck ); // show first card
else if ( e.getSource() == controls[ 1 ] )
cardManager.next( deck ); // show next card
else if ( e.getSource() == controls[ 2 ] )
cardManager.previous( deck ); // show previous card
else if ( e.getSource() == controls[ 3 ] )
cardManager.last( deck ); // show last card
}

public static void main( String args[] )
{
CardDeck cardDeckDemo = new CardDeck();

cardDeckDemo.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
} );
}
}

AWT(Show colors Using JFrame)

// Demonstrating Colors
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class ShowColors extends JFrame
{
public ShowColors()
{
super( "Using colors" );

setSize( 400, 130 );
show();
}

public void paint( Graphics g )
{
// set new drawing color using integers
g.setColor( new Color( 255, 0, 0 ) );
g.fillRect( 25, 25, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 40 );

// set new drawing color using floats
g.setColor( new Color( 0.0f, 1.0f, 0.0f ) );
g.fillRect( 25, 50, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 65 );

// set new drawing color using static Color objects
g.setColor( Color.blue );
g.fillRect( 25, 75, 100, 20 );
g.drawString( "Current RGB: " + g.getColor(), 130, 90 );

// display individual RGB values
Color c = Color.magenta;
g.setColor( c );
g.fillRect( 25, 100, 100, 20 );
g.drawString( "RGB values: " + c.getRed() + ", " + c.getGreen() + ", " + c.getBlue(), 130, 115 );
}

public static void main( String args[] )
{
ShowColors app = new ShowColors();

app.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
} );
}
}

AWT(Painter Using JFrame)

// Program paints shapes and text of different fonts and colors.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class Painter2 extends JFrame {
private int topX, topY, width, fontSize,
height, bottomX, bottomY, shape;
private boolean clear, textOn, filled;
private Color drawingColor;
private String font;
private JTextField text;
private JPanel panel1, panel2, panel3, panel4;
private JRadioButton ovalBox, rectBox, lineBox;
private ButtonGroup shapeGroup;
private JCheckBox fillBox;
private JComboBox colorList, fontList, sizeList;
private JButton clearButton;
private String colorNames[] = { "Black", "Green", "Blue",
"Red", "Cyan" };
private Color colors[] = { Color.black, Color.green, Color.blue,
Color.red, Color.cyan };
private String fontNames[] = { "Serif", "SansSerif", "Monospaced" };
private String sizeNames[] = { "9", "10", "22", "72" };
private int sizes[] = { 9, 10, 22, 72 };
private final int OVAL = 1, LINE = 2, RECT = 3;

private ToolWindow tools;

// Painter2 constructor
public Painter2()
{
super( "Painting Window" );

addMouseListener( new MouseHandler() );

// set defaults for painting
drawingColor = Color.black;
shape = OVAL;
font = "Serif";
fontSize = 9;

setDefaultCloseOperation( EXIT_ON_CLOSE );
setBackground( Color.white );
setSize( 300, 300 );
show();

// create new ToolWindow
tools = new ToolWindow();

} // end constructor

// paint the new window. super is not called so
// that the previous images will not be erased.
public void paint( Graphics g )
{
g.setColor( drawingColor );

// draw text
if ( textOn ) {
g.setFont( new Font( font, Font.PLAIN, fontSize ) );
g.drawString( text.getText(), topX, topY );
textOn = false;
return;

} // end if statement

// set shape's top left coordinates
if ( shape != LINE ) {
topX = Math.min( topX, bottomX );
topY = Math.min( topY, bottomY );

} // end if statement

// draw filled shape
if ( filled && shape != LINE )

switch ( shape ) {

case OVAL:
g.fillOval( topX, topY, width, height );
break;

case RECT:
g.fillRect( topX, topY, width, height );
break;

} // end switch statement

// draw unfilled shapes
else

switch ( shape ) {

case OVAL:
g.drawOval( topX, topY, width, height );
break;

case LINE:
g.drawLine( topX, topY, bottomX, bottomY );
break;

case RECT:
g.drawRect( topX, topY, width, height );
break;

} // ens switch statement

// clear background
if ( clear == true ) {
g.setColor( Color.white );
g.fillRect( 0, 0, getSize().width, getSize().height );
clear = false;

} // end if statement

} // end method paint

// inner class for window containing GUI
private class ToolWindow extends JFrame {

// ToolWindow constructor
public ToolWindow()
{
super( "Tool Window" );

// set up to edit text
text = new JTextField( "Text", 25 );

text.addActionListener(

// anonymous inner class to handle text drawing
new ActionListener () {

public void actionPerformed( ActionEvent event )
{
textOn = true;
repaint();

} // end actionPerformed method

} // end anonymous inner class

); // end call to addActionListener

// set up to choose font
fontList = new JComboBox( fontNames );
fontList.setMaximumRowCount( 3 );

fontList.addItemListener(

// anonymous inner class to select font
new ItemListener() {

// change font
public void itemStateChanged( ItemEvent event )
{
font =
fontNames[ fontList.getSelectedIndex() ];

} // end itemStateChanged method

} // end anonymous inner class

); // end call to addItemListener

// set up to choose font size
sizeList = new JComboBox( sizeNames );
sizeList.setMaximumRowCount( 3 );

sizeList.addItemListener(

// anonymous inner class to select font size
new ItemListener() {

// change font size
public void itemStateChanged( ItemEvent event )
{
fontSize =
sizes[ sizeList.getSelectedIndex() ];

} // end itemStateChanged method

} // end anonymous inner class

); // end call to addItemListener

// set up to choose color
colorList = new JComboBox( colorNames );
colorList.setMaximumRowCount( 3 );

colorList.addItemListener(

// anonymous inner class to select color
new ItemListener() {

// change color
public void itemStateChanged( ItemEvent event )
{
drawingColor =
colors[ colorList.getSelectedIndex() ];

} // end itemStateChanged method

} // end anonymous inner class

); // end call to addItemListener

// set up clear button
clearButton = new JButton( "Clear" );
clearButton.addActionListener(
new ClearButtonHandler() );

// set up to choose filled
fillBox = new JCheckBox( "Filled" );
FillBoxHandler fillHandle = new FillBoxHandler();
fillBox.addItemListener( fillHandle );

// set up to choose shapes
ovalBox = new JRadioButton( "Oval", true );
lineBox = new JRadioButton( "Line", false );
rectBox = new JRadioButton( "Rectangle", false );
RadioButtonHandler handler = new RadioButtonHandler();
ovalBox.addItemListener( handler );
lineBox.addItemListener( handler );
rectBox.addItemListener( handler );
shapeGroup = new ButtonGroup();
shapeGroup.add(ovalBox);
shapeGroup.add(lineBox);
shapeGroup.add(rectBox);

// set up GUI layout
panel1 = new JPanel();
panel2 = new JPanel();
panel3 = new JPanel();
panel4 = new JPanel();

panel1.setLayout( new GridLayout( 1, 4 ) );
panel2.setLayout( new GridLayout( 1, 3 ) );
panel3.setLayout( new FlowLayout() );
panel4.setLayout( new FlowLayout() );

panel1.add( ovalBox );
panel1.add( lineBox );
panel1.add( rectBox );
panel1.add( fillBox );
panel2.add( new JScrollPane( colorList ) );
panel2.add( new JScrollPane( fontList ) );
panel2.add( new JScrollPane( sizeList ) );
panel3.add( text );
panel4.add( clearButton );

Container container = getContentPane();
container.setLayout( new FlowLayout() );
container.add( panel1 );
container.add( panel2 );
container.add( panel3 );
container.add( panel4 );

setDefaultCloseOperation( EXIT_ON_CLOSE );
setSize( 350, 175 );
setLocation( 300, 0 );
setVisible( true );

} // end ToolWindow constructor

} // end inner class ToolWindow

// set coordinate and dimension values
private class MouseHandler extends MouseAdapter {

public void mousePressed( MouseEvent event )
{
topX = event.getX();
topY = event.getY();

} // end mousePressed method

public void mouseReleased( MouseEvent event )
{
bottomX = event.getX();
bottomY = event.getY();
width = Math.abs( topX - bottomX );
height = Math.abs( topY - bottomY );

repaint();

} // end mouseReleased method

} // end inner class MouseHandler

// clear background
private class ClearButtonHandler implements ActionListener {

public void actionPerformed( ActionEvent event )
{
clear = true;
repaint();

} // end actionPerformed method

} // end inner class ClearButtonHandler

// determine which type of shape to draw
private class RadioButtonHandler implements ItemListener {

public void itemStateChanged( ItemEvent event )
{
if ( event.getSource() == ovalBox )
shape = OVAL;

else if ( event.getSource() == lineBox )
shape = LINE;

else if ( event.getSource() == rectBox )
shape = RECT;

} // end itemStateChanged method

} // end inner class RadioButtonHandler

// determine if shape should be filled
private class FillBoxHandler implements ItemListener {

public void itemStateChanged( ItemEvent event )
{
if ( event.getStateChange() == ItemEvent.SELECTED )
filled = true;

else
filled = false;

} // end ItemStateChanged method

} // end inner class FillBoxHandler

// execute application
public static void main( String args[] )
{
Painter2 application = new Painter2();

application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

} // end main method

} // end class Painter2

AWT(Painter)

// Using class MouseMotionAdapter.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class Painter extends JFrame
{
private int xValue = -10, yValue = -10;

public Painter()
{
super( "A simple paint program" );

getContentPane().add( new Label( "Drag the mouse to draw" ), BorderLayout.SOUTH );

addMouseMotionListener( new MouseMotionAdapter()
{
public void mouseDragged( MouseEvent e )
{
xValue = e.getX();
yValue = e.getY();
repaint();
}
} );

setSize( 300, 150 );
show();
}

public void paint( Graphics g )
{
g.fillOval( xValue, yValue, 4, 4 );
}

public static void main( String args[] )
{
Painter app = new Painter();

app.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
} );
}
}

AWT(Mouse Tracker Usinng JJrame and Mouse Events)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class MouseTracker extends JFrame implements MouseListener, MouseMotionListener
{
private JLabel statusBar;

public MouseTracker()
{
super( "Demonstrating Mouse Events" );

statusBar = new JLabel();
getContentPane().add( statusBar, BorderLayout.SOUTH );

// application listens to its own mouse events
addMouseListener( this );
addMouseMotionListener( this );

setSize( 275, 100 );
show();
}

// MouseListener event handlers
public void mouseClicked( MouseEvent e )
{
statusBar.setText( "Clicked at [" + e.getX() + ", " + e.getY() + "]" );
}

public void mousePressed( MouseEvent e )
{
statusBar.setText( "Pressed at [" + e.getX() + ", " + e.getY() + "]" );
}

public void mouseReleased( MouseEvent e )
{
statusBar.setText( "Released at [" + e.getX() + ", " + e.getY() + "]" );
}

public void mouseEntered( MouseEvent e )
{
statusBar.setText( "Mouse in window" );
}

public void mouseExited( MouseEvent e )
{
statusBar.setText( "Mouse outside window" );
}

// MouseMotionListener event handlers
public void mouseDragged( MouseEvent e )
{
statusBar.setText( "Dragged at [" + e.getX() + ", " + e.getY() + "]" );
}

public void mouseMoved( MouseEvent e )
{
statusBar.setText( "Moved at [" + e.getX() + ", " + e.getY() + "]" );
}

public static void main( String args[] )
{
MouseTracker app = new MouseTracker();

app.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
} );
}
}

AWT(Demonstrating Keystroke Events)

// Demonstrating keystroke events.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class KeyDemo extends JFrame implements KeyListener
{
private String line1 = "", line2 = "";
private String line3 = "";
private JTextArea textArea;

public KeyDemo()
{
super( "Demonstrating Keystroke Events" );

textArea = new JTextArea( 10, 15 );
textArea.setText( "Press any key on the keyboard..." );
textArea.setEnabled( false );

// allow frame to process Key events
addKeyListener( this );

getContentPane().add( textArea );

setSize( 350, 100 );
show();
}

public void keyPressed( KeyEvent e )
{
line1 = "Key pressed: " + e.getKeyText( e.getKeyCode() );
setLines2and3( e );
}

public void keyReleased( KeyEvent e )
{
line1 = "Key released: " + e.getKeyText( e.getKeyCode() );
setLines2and3( e );
}

public void keyTyped( KeyEvent e )
{
line1 = "Key typed: " + e.getKeyChar();
setLines2and3( e );
}

private void setLines2and3( KeyEvent e )
{
line2 = "This key is " + ( e.isActionKey() ? "" : "not " ) + "an action key";

String temp = e.getKeyModifiersText( e.getModifiers() );

line3 = "Modifier keys pressed: " + ( temp.equals( "" ) ? "none" : temp );

textArea.setText( line1 + "\n" + line2 + "\n" + line3 + "\n" );
}

public static void main( String args[] )
{
KeyDemo app = new KeyDemo();

app.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
} );
}
}

AWT(Example For GridLayout )

// Demonstrating GridLayout.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class GridLayoutDemo extends JFrame
implements ActionListener {
private JButton b[];
private String names[] =
{ "one", "two", "three", "four", "five", "six" };
private boolean toggle = true;
private Container c;
private GridLayout grid1, grid2;

public GridLayoutDemo()
{
super( "GridLayout Demo" );

grid1 = new GridLayout( 2, 3, 5, 5 );
grid2 = new GridLayout( 3, 2 );

c = getContentPane();
c.setLayout( grid1 );

// create and add buttons
b = new JButton[ names.length ];

for (int i = 0; i < names.length; i++ ) {
b[ i ] = new JButton( names[ i ] );
b[ i ].addActionListener( this );
c.add( b[ i ] );
}

setSize( 300, 150 );
show();
}

public void actionPerformed( ActionEvent e )
{
if ( toggle )
c.setLayout( grid2 );
else
c.setLayout( grid1 );

toggle = !toggle;
c.validate();
}

public static void main( String args[] )
{
GridLayoutDemo app = new GridLayoutDemo();

app.addWindowListener(
new WindowAdapter() {

public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}

AWT(Draw random lines, rectangles and ovals)

// Draw random lines, rectangles and ovals
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class DrawShapes extends JApplet
{
private JButton choices[];
private String names[] = { "Line", "Rectangle", "Oval" };
private JPanel buttonPanel;
private DrawPanel drawingArea;
private int width = 300, height = 200;

public void init()
{
drawingArea = new DrawPanel( width, height );

choices = new JButton[ names.length ];
buttonPanel = new JPanel();
buttonPanel.setLayout( new GridLayout( 1, choices.length ) );
ButtonHandler handler = new ButtonHandler();

for ( int i = 0; i < c =" getContentPane();" width =" (">= 0 ? w : 300 );
}

public void setHeight( int h )
{
height = ( h >= 0 ? h : 200 );
}

public static void main( String args[] )
{
int width, height;

if ( args.length != 2 )
{
// no command-line arguments
width = 300;
height = 200;
}
else
{
width = Integer.parseInt( args[ 0 ] );
height = Integer.parseInt( args[ 1 ] );
}

// create window in which applet will execute
JFrame applicationWindow = new JFrame( "An applet running as an application" );

applicationWindow.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
} );

// create one applet instance
DrawShapes appletObject = new DrawShapes();
appletObject.setWidth( width );
appletObject.setHeight( height );

// call applet's init and start methods
appletObject.init();
appletObject.start();

// attach applet to center of window
applicationWindow.getContentPane().add( appletObject );

// set the window's size
applicationWindow.setSize( width, height );

// showing the window causes all GUI components
// attached to the window to be painted
applicationWindow.show();
}

private class ButtonHandler implements ActionListener
{
public void actionPerformed( ActionEvent e )
{
for ( int i = 0; i < currentchoice =" -1;" width =" 100," height =" 100;" width =" (">= 0 ? w : 100 );
height = ( h >= 0 ? h : 100 );
}

public void paintComponent( Graphics g )
{
super.paintComponent( g );

switch( currentChoice )
{
case 0:
g.drawLine( randomX(), randomY(), randomX(), randomY() );
break;
case 1:
g.drawRect( randomX(), randomY(), randomX(), randomY() );
break;
case 2:
g.drawOval( randomX(), randomY(), randomX(), randomY() );
break;
}
}

public void setCurrentChoice( int c )
{
currentChoice = c;
repaint();
}
private int randomX()
{
return (int) ( Math.random() * width );
}

private int randomY()
{
return (int) ( Math.random() * height );
}
}

AWT(DrawPolygons)

// Drawing polygons
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class DrawPolygons extends JFrame
{
public DrawPolygons()
{
super( "Drawing Polygons" );
setSize( 275, 230 );
show();
}

public void paint( Graphics g )
{
int xValues[] = { 20, 40, 50, 30, 20, 15 };
int yValues[] = { 50, 50, 60, 80, 80, 60 };
Polygon poly1 = new Polygon( xValues, yValues, 6 );

g.drawPolygon( poly1 );

int xValues2[] = { 70, 90, 100, 80, 70, 65, 60 };
int yValues2[] = { 100, 100, 110, 110, 130, 110, 90 };

g.drawPolyline( xValues2, yValues2, 7 );

int xValues3[] = { 120, 140, 150, 190 };
int yValues3[] = { 40, 70, 80, 60 };

g.fillPolygon( xValues3, yValues3, 4 );

Polygon poly2 = new Polygon();
poly2.addPoint( 165, 135 );
poly2.addPoint( 175, 150 );
poly2.addPoint( 270, 200 );
poly2.addPoint( 200, 220 );
poly2.addPoint( 130, 180 );

g.fillPolygon( poly2 );
}

public static void main( String args[] )
{
DrawPolygons app = new DrawPolygons();

app.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
} );
}
}

AWT(DrawArcs Using JFrame)

// Drawing arcs
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class DrawArcs extends JFrame
{
public DrawArcs()
{
super( "Drawing Arcs" );
setSize( 300, 170 );
show();
}

public void paint( Graphics g )
{
// start at 0 and sweep 360 degrees
g.setColor( Color.yellow );
g.drawRect( 15, 35, 80, 80 );
g.setColor( Color.black );
g.drawArc( 15, 35, 80, 80, 0, 360 );
// start at 0 and sweep 110 degrees
g.setColor( Color.yellow );
g.drawRect( 100, 35, 80, 80 );
g.setColor( Color.black );
g.drawArc( 100, 35, 80, 80, 0, 110 );

// start at 0 and sweep -270 degrees
g.setColor( Color.yellow );
g.drawRect( 185, 35, 80, 80 );
g.setColor( Color.black );
g.drawArc( 185, 35, 80, 80, 0, -270 );

// start at 0 and sweep 360 degrees
g.fillArc( 15, 120, 80, 40, 0, 360 );

// start at 270 and sweep -90 degrees
g.fillArc( 100, 120, 80, 40, 270, -90 );

// start at 0 and sweep -270 degrees
g.fillArc( 185, 120, 80, 40, 0, -270 );
}

public static void main( String args[] )
{
DrawArcs app = new DrawArcs();

app.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
} );
}
}

AWT(CheckBox Using JFrame)

// Creating Checkbox buttons.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CheckBoxTest extends JFrame {
private JTextField t;
private JCheckBox bold, italic;

public CheckBoxTest()
{
super( "JCheckBox Test" );

Container c = getContentPane();
c.setLayout(new FlowLayout());

t = new JTextField( "Watch the font style change", 20 );
t.setFont( new Font( "TimesRoman", Font.PLAIN, 14 ) );
c.add( t );

// create checkbox objects
bold = new JCheckBox( "Bold" );
c.add( bold );

italic = new JCheckBox( "Italic" );
c.add( italic );

CheckBoxHandler handler = new CheckBoxHandler();
bold.addItemListener( handler );
italic.addItemListener( handler );

addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);

setSize( 275, 100 );
show();
}

public static void main( String args[] )
{
new CheckBoxTest();
}

private class CheckBoxHandler implements ItemListener {
private int valBold = Font.PLAIN;
private int valItalic = Font.PLAIN;
public void itemStateChanged( ItemEvent e )
{
if ( e.getSource() == bold )
if ( e.getStateChange() == ItemEvent.SELECTED )
valBold = Font.BOLD;
else
valBold = Font.PLAIN;

if ( e.getSource() == italic )
if ( e.getStateChange() == ItemEvent.SELECTED )
valItalic = Font.ITALIC;
else
valItalic = Font.PLAIN;

t.setFont(
new Font( "TimesRoman", valBold + valItalic, 14 ) );
t.repaint();
}
}
}

AWT(CheckboxGroups Using Applet)

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

public class CheckboxGroups extends Applet {
public void init() {
setLayout(new GridLayout(4, 2));
setBackground(Color.lightGray);
setFont(new Font("Serif", Font.BOLD, 16));
add(new Label("Flavor", Label.CENTER));
add(new Label("Toppings", Label.CENTER));
CheckboxGroup flavorGroup = new CheckboxGroup();
add(new Checkbox("Vanilla", flavorGroup, true));
add(new Checkbox("Colored Sprinkles"));
add(new Checkbox("Chocolate", flavorGroup, false));
add(new Checkbox("Cashews"));
add(new Checkbox("Strawberry", flavorGroup, false));
add(new Checkbox("Kiwi"));
}
}
/*
<HTML>
<HEAD>
<TITLE>CheckboxGroups</TITLE>
</HEAD>

<BODY>
<H1>CheckboxGroups</H1>

<APPLET CODE="CheckboxGroups.class" WIDTH=400 HEIGHT=150>
</APPLET>

</BODY>
</HTML>
*/

Run
appletviewer CheckboxGroups.java

AWT(Example For BoxLayout Using JFrame)

// Demonstrating BoxLayout.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class BoxLayoutDemo extends JFrame {
public BoxLayoutDemo()
{
super( "Demostrating BoxLayout" );
final int SIZE = 3;

Container c = getContentPane();
c.setLayout( new BorderLayout( 30, 30 ) );

Box boxes[] = new Box[ 4 ];

boxes[ 0 ] = Box.createHorizontalBox();
boxes[ 1 ] = Box.createVerticalBox();
boxes[ 2 ] = Box.createHorizontalBox();
boxes[ 3 ] = Box.createVerticalBox();

// add buttons to boxes[ 0 ]
for ( int i = 0; i < SIZE; i++ )
boxes[ 0 ].add( new JButton( "boxes[0]: " + i ) );

// create strut and add buttons to boxes[ 1 ]
for ( int i = 0; i < SIZE; i++ ) {
boxes[ 1 ].add( Box.createVerticalStrut( 25 ) );
boxes[ 1 ].add( new JButton( "boxes[1]: " + i ) );
}

// create horizontal glue and add buttons to boxes[ 2 ]
for ( int i = 0; i < SIZE; i++ ) {
boxes[ 2 ].add( Box.createHorizontalGlue() );
boxes[ 2 ].add( new JButton( "boxes[2]: " + i ) );
}

// create rigid area and add buttons to boxes[ 3 ]
for ( int i = 0; i < SIZE; i++ ) {
boxes[ 3 ].add(
Box.createRigidArea( new Dimension( 12, 8 ) ) );
boxes[ 3 ].add( new JButton( "boxes[3]: " + i ) );
}

// create horizontal glue and add buttons to panel
JPanel panel = new JPanel();
panel.setLayout(
new BoxLayout( panel, BoxLayout.Y_AXIS ) );

for ( int i = 0; i < SIZE; i++ ) {
panel.add( Box.createGlue() );
panel.add( new JButton( "panel: " + i ) );
}

// place panels on frame
c.add( boxes[ 0 ], BorderLayout.NORTH );
c.add( boxes[ 1 ], BorderLayout.EAST );
c.add( boxes[ 2 ], BorderLayout.SOUTH );
c.add( boxes[ 3 ], BorderLayout.WEST );
c.add( panel, BorderLayout.CENTER );

setSize( 350, 300 );
show();
}
public static void main( String args[] )
{
BoxLayoutDemo app = new BoxLayoutDemo();

app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}

AWT(Demonstrating BorderLayout)

// Demonstrating BorderLayout.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BorderLayoutDemo extends JFrame
implements ActionListener {
private JButton b[];
private String names[] =
{ "Hide North", "Hide South", "Hide East",
"Hide West", "Hide Center" };
private BorderLayout layout;

public BorderLayoutDemo()
{
super( "BorderLayout Demo" );

layout = new BorderLayout( 5, 5 );

Container c = getContentPane();
c.setLayout( layout );

// instantiate button objects
b = new JButton[ names.length ];

for ( int i = 0; i < names.length; i++ ) {
b[ i ] = new JButton( names[ i ] );
b[ i ].addActionListener( this );
}

// order not important
c.add( b[ 0 ], BorderLayout.NORTH ); // North position
c.add( b[ 1 ], BorderLayout.SOUTH ); // South position
c.add( b[ 2 ], BorderLayout.EAST ); // East position
c.add( b[ 3 ], BorderLayout.WEST ); // West position
c.add( b[ 4 ], BorderLayout.CENTER ); // Center position

setSize( 300, 200 );
show();
}

public void actionPerformed( ActionEvent e )
{
for ( int i = 0; i < b.length; i++ )
if ( e.getSource() == b[ i ] )
b[ i ].setVisible( false );
else
b[ i ].setVisible( true );

// re-layout the content pane
layout.layoutContainer( getContentPane() );
}

public static void main( String args[] )
{
BorderLayoutDemo app = new BorderLayoutDemo();

app.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
}
);
}
}

AWT(Transparent Background Using JComponent )

import java.awt.*;
import java.util.Date;
import javax.swing.*;
import java.awt.event.*;

public class BGTest1
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Transparent Window");
TransparentBackground bg = new TransparentBackground(frame);
bg.setLayout(new BorderLayout());

JLabel label = new JLabel("This is a label");
bg.add("North",label);
frame.getContentPane().add("Center",bg);
frame.pack();
frame.setSize(300,300);
frame.show();
}
}

class TransparentBackground extends JComponent implements ComponentListener, WindowFocusListener
{
private JFrame frame;
protected Image background;
private long lastupdate = 0;
public boolean refreshRequested = true;
public Robot rbt = null;
public Toolkit tk = null;
public Dimension dim = null;

public TransparentBackground(JFrame frame)
{
this.frame = frame;
updateBackground();
frame.addComponentListener(this);
frame.addWindowFocusListener(this);
}

public void updateBackground()
{
try
{
rbt = new Robot();
tk = Toolkit.getDefaultToolkit();
dim = tk.getScreenSize();
background = rbt.createScreenCapture(
new Rectangle(0,0,(int)dim.getWidth(),(int)dim.getHeight()));
}catch(Exception ex)
{
ex.printStackTrace();
}
}

public void paintComponent(Graphics g)
{
Point pos = this.getLocationOnScreen();
Point offset = new Point(-pos.x,-pos.y);
g.drawImage(background,offset.x,offset.y,null);
}

public void componentShown(ComponentEvent evt) { repaint(); }
public void componentResized(ComponentEvent evt) { repaint(); }
public void componentMoved(ComponentEvent evt) { repaint(); }
public void componentHidden(ComponentEvent evt) { }

public void windowGainedFocus(WindowEvent evt) { refresh(); }
public void windowLostFocus(WindowEvent evt) { refresh(); }

public void refresh(){
if(this.isVisible() && frame.isVisible()) {
repaint();
refreshRequested = true;
lastupdate = new Date().getTime();
}
}
}

AWT(Font)

import java.awt.*;

class FontDemo
{
public static void main(String args[])
{
// Get all font family names
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
String fontNames[] = ge.getAvailableFontFamilyNames();
Font[] fonts = ge.getAllFonts();

for (int i=0; i<fontNames.length; i++) {
//System.out.println(fontNames[i]);
}

// Display some font sizes
String fontSizes[] = new String[64];
for ( int i = 0; i < fontSizes.length; i++ ){
fontSizes[i] = Integer.toString( i+7 );
//System.out.println(fontSizes[i]);
}

// Process each font
for (int i=0; i<fonts.length; i++) {
// Get font~s family and face
String familyName = fonts[i].getFamily();
String faceName = fonts[i].getName();
System.out.println(familyName);
System.out.println(faceName);
}
}
}

AWT(Mouse Paint Using Frame)

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

public class MousePaint extends Frame implements MouseMotionListener
{
private int x1, y1, x2, y2;
public MousePaint()
{
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
dispose();
System.exit(0);
}
});
addMouseMotionListener(this);
setBounds(50,50,400,250);
setVisible(true);
}
public static void main(String[] argv)
{
new MousePaint();
}
public void update(Graphics g)
{
paint(g);
}
public void paint(Graphics g)
{
g.setColor(Color.black);
g.drawLine(x1, y1, x2, y2);
}
public void mouseDragged(MouseEvent me)
{
me.consume();
int x = me.getX();
int y = me.getY();
if ( x1 == 0 )
{
x1 = x;
}
if ( y1 == 0 )
{
y1 = y;
}
x2 = x;
y2 = y;
repaint();
x1 = x2;
y1 = y2;
}
public void mouseMoved(MouseEvent me)
{ }
}

AWT(Example For FocusListener Using Frame)

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

public class FocusListenertest extends Frame implements FocusListener
{
Button b1,b2;

public FocusListenertest()
{
add(b1=new Button ("First"),"South");
add(b2=new Button ("Second"),"North");
b1.addFocusListener(this);
b2.addFocusListener(this);
setSize(200,200);
//pack(); //Takes minimum size for the window
}
public void focusGained(FocusEvent fe) //method of focuslistener
{
if(fe.getSource()==b1)
System.out.println(b1.getLabel()+"gained");
if(fe.getSource()==b2)
System.out.println(b2.getLabel()+"gained");
if(fe.isTemporary())
System.out.println("Temporary Focus");
}
public void focusLost(FocusEvent fe) //in focusevent "getID()"is a method
{
if(fe.getSource()==b1)
System.out.println(b1.getLabel()+"lost");
if(fe.getSource()==b2)
System.out.println(b2.getLabel()+"lost");
}
public static void main(String a[])
{
new FocusListenertest().setVisible(true);
}
}

AWT(Image Canvas Using Canvas )

import java.awt.*;
import java.awt.image.*;

public class ImageCanvas extends Canvas {
Image image;

public ImageCanvas(String name) {
MediaTracker media = new MediaTracker(this);
image = Toolkit.getDefaultToolkit().getImage(name);
media.addImage(image, 0);
try {
media.waitForID(0);
}
catch (Exception e) {}
}

public ImageCanvas(ImageProducer imageProducer) {
image = createImage(imageProducer);
}

public void paint(Graphics g) {
g.drawImage(image, 0,0, this);
}

public static void main(String argv[]) {
if (argv.length < 1) {
System.out.println
("usage: ImageCanvas.class [image file name]");
System.exit(0);
}
Frame frame = new Frame(argv[0]);
frame.setLayout(new BorderLayout());
frame.add("Center", new ImageCanvas(argv[0]));
frame.resize(400,400);
frame.show();
}
}

Run the program
java ImageCanvas for.jpg

SWING(Test Focus Using JFrame)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class TestFocus extends JFrame
{
JButton button; public TestFocus()
{
JPanel panel = new JPanel();
setContentPane( panel );
panel.add( new JTextField( "Focus is on Click Me button", 20 ) );
button = new JButton( "Click Me" );
button.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JDialog dialog = new JDialog1();
}
});
panel.add( button );
// Listen for windowOpened event to set focus
addWindowListener( new WindowAdapter()
{
public void windowOpened( WindowEvent e )
{
button.requestFocus();
}
});
}
public static void main(String[] args)
{
TestFocus frame = new TestFocus();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
// frame.button.requestFocus();
}
class JDialog1 extends JDialog
{
public JDialog1()
{
JPanel panel = new JPanel();
setContentPane( panel);
panel.add( new JTextField( "Focus is on next Text Field", 20) );
final JTextField tf1 = new JTextField(9);
panel.add( tf1 );
pack();
// Use invokeLater AFTER the dialog is shown
setVisible( true );
SwingUtilities.invokeLater( new Runnable()
{
public void run()
{
tf1.requestFocus();
}
});
}
}
}

SWING(Image Processing Using JDialog)

import java.io.*;
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import javax.imageio.*;
public class RobotImage extends javax.swing.JDialog
{
public RobotImage(java.awt.Frame parent, boolean modal)
{
super(parent, modal);
initComponents();
jTextPane.getCaret().setBlinkRate(0);
}
private void initComponents()
{
jTextPane = new javax.swing.JTextPane();
addWindowListener(new java.awt.event.WindowAdapter()
{
public void windowClosing(java.awt.event.WindowEvent evt)
{
closeDialog(evt);
}
});
getContentPane().add(jTextPane, java.awt.BorderLayout.CENTER);
pack();
}
private void closeDialog(java.awt.event.WindowEvent evt)
{
try
{
jTextPane.getCaret().setVisible(false);
jTextPane.paintImmediately(jTextPane.getBounds());
BufferedImage bi = new Robot().createScreenCapture(this.getBounds());
ImageIO.write(bi, "jpg", new File("t.jpg"));
}
catch (Exception ex)
{
// nothing
}
setVisible(false);
dispose();
}
public static void main(String args[])
{
new RobotImage(new javax.swing.JFrame(), true).show();
}
private javax.swing.JTextPane jTextPane;
}

SWING(Example For JFrame,JButton)

import javax.swing.*;
import java.awt.event.*;

public class Test
{
boolean firstAdapterCalled = false;
boolean secondAdapterCalled = false;
MyFirstAdapter ma1;
MySecondAdapter ma2;
public Test()
{
JFrame frame = new JFrame ("Test");
JButton butt = new JButton("Press Me");
frame.getContentPane().add(butt);
frame.pack();
frame.setVisible(true);
ma1 = new MyFirstAdapter();
ma2 = new MySecondAdapter();
butt.addMouseListener(ma1);
butt.addMouseListener(ma2);
}
public static void main (String [] args)
{
Test t = new Test();
}

class MyFirstAdapter extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
System.out.println("Called first adapter");
firstAdapterCalled = true;
ma2.mouseClicked(e);
}
}
class MySecondAdapter extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
if (!firstAdapterCalled)
{
System.out.println("First adapter not called yet...");
return;
}
System.out.println("Second adapter called");
firstAdapterCalled = false;
}
}
}

SWING(Color Renderer Using JLabel)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;

class ColorRenderer extends JLabel implements TableCellRenderer
{
private String columnName;
public ColorRenderer(String column)
{
this.columnName = column;
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected, boolean hasFocus, int row, int column)
{
Object columnValue=table.getValueAt(row,table.getColumnModel().getColumnIndex(columnName));

if (value != null) setText(value.toString());
if(isSelected)
{
setBackground(table.getSelectionBackground());
setForeground(table.getSelectionForeground());
}
else
{
setBackground(table.getBackground());
setForeground(table.getForeground());
if (columnValue.equals("1")) setBackground(java.awt.Color.pink);
if (columnValue.equals("2")) setBackground(java.awt.Color.green);
if (columnValue.equals("3")) setBackground(java.awt.Color.red);
if (columnValue.equals("4")) setBackground(java.awt.Color.blue);

}
return this;
}
}

public class TableRowColor2 extends JFrame
{
public TableRowColor2()
{
JTable table=new JTable(new DefaultTableModel(new Object[][]{
{"1","2","3","4"},
{"2","3","4","5"},
{"3","4","5","6"},
{"4","5","6","7"}},
new Object[]{"A","B","C","D"}));

ColorRenderer cr=new ColorRenderer("A");

//Adding this line of code will color only the first column and different colors for
//each row and dont forget to comment the for loop
//table.getColumnModel().getColumn(0).setCellRenderer(cr);

for (int i=0;i
table.getColumn(table.getColumnName(i)).setCellRenderer(cr);
JScrollPane scroll=new JScrollPane(table);
this.setContentPane(scroll);
this.setBounds(100,50,300,150);
}
public static void main (String arg[])
{
TableRowColor2 tes = new TableRowColor2();
tes.setVisible(true);
tes.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


Save as TableRowColor2.java

SWING(TableColumnColor Using JFrame)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;

public class TableColumnColor extends JFrame
{
String[] columnNames = {"Column1", "Column2","Column3"};
Object[][] data = {
{"copy.gif", "Image1","dd" },
{"save.gif", "Image2" ,"dd"},
{"script.gif", "Image3","dd" },
{"task.gif", "Image4" ,"dd"},
};

public TableColumnColor()
{
DefaultTableModel dtm = new DefaultTableModel(data,columnNames);
JTable table=new JTable(dtm)
{
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
{
Component component = super.prepareRenderer(renderer,row,column);

if(column == 0)
{
component.setBackground(Color.yellow);
}
if(column == 1)
{
component.setBackground(Color.red);
}
if(column == 2)
{
component.setBackground(Color.pink);
}
return component;
}
};

JScrollPane scroll=new JScrollPane(table);
this.setContentPane(scroll);
this.setBounds(100,50,300,150);
}
public static void main (String arg[])
{
TableColumnColor tes = new TableColumnColor();
tes.setVisible(true);
tes.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

SWING(Notepad Project)

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.Keymap;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.sql.Date;
import java.text.MessageFormat;
import java.util.Locale;

public class Notepad extends JPanel implements ActionListener
{
JMenuItem New,save,saveas,exit,open,cut,copy,paste,selectall,font,wron,wroff,srch,dt;
static JTextArea textArea;
JFileChooser fc;
String s1;
public Notepad()
{
super(new BorderLayout());
textArea = new JTextArea(5, 30);
textArea.setEditable(true);
JScrollPane scrollPane = new JScrollPane(textArea);
setPreferredSize(new Dimension(500, 250));
add(scrollPane,BorderLayout.CENTER);
}

public JMenuBar createMenuBar()
{
JMenuBar menuBar;
menuBar = new JMenuBar();
JMenu mainMenu1 = new JMenu("File");
menuBar.add(mainMenu1);
mainMenu1.setMnemonic(KeyEvent.VK_F);
New = new JMenuItem("New",KeyEvent.VK_N);
New.addActionListener((ActionListener) this);
mainMenu1.add(New);
open = new JMenuItem("Open",KeyEvent.VK_O);
open.addActionListener(this);
mainMenu1.add(open);
save = new JMenuItem("Save",KeyEvent.VK_S);
save.addActionListener(this);
mainMenu1.add(save);
saveas = new JMenuItem("SaveAs",KeyEvent.VK_S);
saveas.addActionListener(this);
mainMenu1.add(saveas);
exit = new JMenuItem("Exit",KeyEvent.VK_X);
exit.addActionListener(this);
mainMenu1.add(exit);
JMenu mainMenu2=new JMenu("Edit");
menuBar.add(mainMenu2);
mainMenu2.setMnemonic(KeyEvent.VK_E);
cut = new JMenuItem("Cut",KeyEvent.VK_CUT);
cut.addActionListener(this);
mainMenu2.add(cut);
copy = new JMenuItem("Copy",KeyEvent.VK_COPY);
copy.addActionListener(this);
mainMenu2.add(copy);
paste = new JMenuItem("Paste",KeyEvent.VK_PASTE);
paste.addActionListener(this);
mainMenu2.add(paste);
selectall = new JMenuItem("SelectAll");
selectall.addActionListener(this);
mainMenu2.add(selectall);
srch = new JMenuItem("Find");
srch.addActionListener(this);
mainMenu2.add(srch);
JMenu mainMenu3=new JMenu("Format");
menuBar.add(mainMenu3);
wron = new JMenuItem("Word Wrap On");
wron.addActionListener(this);
mainMenu3.add(wron);
wroff = new JMenuItem("Word Wrap Off");
wroff.addActionListener(this);
mainMenu3.add(wroff);
font = new JMenuItem("Font",KeyEvent.VK_PASTE);
font.addActionListener(this);
mainMenu3.add(font);
dt = new JMenuItem("Date/Time ",KeyEvent.VK_D);
dt.addActionListener(this);
mainMenu3.add(dt);
textArea.setWrapStyleWord(false);
return menuBar;
}
public void actionPerformed(ActionEvent e)
{
fc= new JFileChooser();
if (e.getSource() == open) {
int returnVal = fc.showOpenDialog(Notepad.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
FileReader fr = new FileReader(file);
textArea.read(fr,null);
fr.close();
}
catch (Exception ev) { System.err.println("Could not load page: "+file);
}
}
textArea.setCaretPosition(textArea.getDocument().getLength());

} else if (e.getSource() == save) {
int returnVal = fc.showSaveDialog(Notepad.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
FileWriter fw = new FileWriter(file);
textArea.write(fw);
fw.close();
}
catch(Exception ev)
{
System.err.println("Could not save page: "+file);
}
}
textArea.setCaretPosition(textArea.getDocument().getLength());
}
else if(e.getSource()==New)
{
s1="";
textArea.setText(s1);
}
else if(e.getSource()==cut){
textArea.cut();

}else if(e.getSource()==copy)
{
textArea.copy();
}else if(e.getSource()==paste)
{
textArea.paste();
}
else if(e.getSource()==exit)
{
System.exit(0);
}
else if(e.getSource()==selectall)
{
textArea.selectAll();
}
else if(e.getSource()==font)
{
String str;
str=textArea.getSelectedText();
new fnt(str);
}
else if(e.getSource()==wron)
{
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
}
else if(e.getSource()==wroff)
{
System.out.println("This is off area ");
textArea.setLineWrap(false);
textArea.setWrapStyleWord(false);
}
else if(e.getSource()== srch)
{
new find(this);
}
else if(e.getSource()==dt)
{
String pattern = " {0, time, short}" + " {0, date, long}." ;
StringWriter sw = new StringWriter(100);
PrintWriter out = new PrintWriter(sw, true);
MessageFormat formatter = new MessageFormat(pattern, Locale.US);
Object messageArgs[] = {new Date(0),new Double(9000.12)};
out.print(formatter.format(messageArgs));
out.close();
textArea.append(sw.toString());
}
else if(e.getSource()==saveas) {
int returnVal = fc.showDialog(this,"SaveAs");
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try
{
s1="";
s1=textArea.getText();
FileWriter fw=new FileWriter(file);
StringReader sr=new StringReader(s1);
BufferedReader br=new BufferedReader(sr);
String lr="";
while((lr=br.readLine())!=null)
{
fw.write(lr+" ");
}
fw.close();
}catch(Exception pe){}
}
}
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("Untitled-Notepad");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Notepad note = new Notepad();
frame.setJMenuBar(note.createMenuBar());
note.setOpaque(true);
frame.setContentPane(note);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}




public class fnt extends JDialog implements ActionListener
{
JDialog dialog;
JLabel lab1,lab2,lab3;
JButton button1,button2;
JList lst1,lst2,lst3;
String[] names={"Arial","Times New Roman","Scanserif"};
String[] types={"Regular","Bold","Italic"};
String[] sizes={"8","10","12","14","16","18","20"};
public fnt(String s)
{
dialog = new JDialog();
lst1=new JList(names);
lst1.setSelectedIndex(0);
lst2=new JList(types);
lst2.setSelectedIndex(0);
lst3=new JList(sizes);
lst3.setSelectedIndex(0);
lab1=new JLabel("Font Name");
dialog.add(lst1);
lab2=new JLabel("Font Type");
dialog.add(lst2);
lab3=new JLabel("Font Size");
dialog.add(lst3);
button1= new JButton("Ok");
dialog.add(button1);
button2=new JButton("Cancel");
dialog.add(button2);
button1.addActionListener(this);
button2.addActionListener(this);
dialog.setLayout(new FlowLayout());
dialog.setSize(300,300);
dialog.setVisible(true);
}
public void actionPerformed(ActionEvent fe)
{
String str1,str2,str3;
int st=0;
str1=lst1.getSelectedValue().toString();
str2=lst2.getSelectedValue().toString();
str3=lst3.getSelectedValue().toString();
if(str2=="Regular")
{
st=Font.PLAIN;
}
if(str2=="Bold")
{
st=Font.BOLD;
}
if(str2=="Italic")
{
st=Font.ITALIC;
}
str3=lst3.getSelectedValue().toString();
int size=Integer.parseInt(str3);
if(fe.getSource()==button1)
{
Font fnt=new Font(str1,st,size);
Notepad.textArea.setFont(fnt);
dialog.setVisible(false);
}
if(fe.getSource()==button2)
{
System.exit(0);
}
}
}
//Find Class
public class find extends JDialog implements ActionListener
{
JPanel jPanel = new JPanel();
JButton find_next = new JButton();
JButton replace = new JButton();
JButton replaceAll = new JButton();
JButton cancel = new JButton();
JTextField find = new JTextField();
JTextField replacewith = new JTextField();
JLabel jLabel1 = new JLabel();
JLabel jLabel2 = new JLabel();
JCheckBox matchcase = new JCheckBox();
int pos;
int count;
int a;
int newcounter;
int jass=0;

public find(Notepad mnote)
{
find_next.setText("Find Next");
replace.setText (" Replace ");
replaceAll.setText("Replace All");
cancel.setText (" Cancel ");
jLabel1.setText("Find Text:");
jLabel2.setText("Replace With:");
matchcase.setText("Match Case");
JPanel jPanela = new JPanel();
JPanel jPanelb = new JPanel();
JPanel jPanelc = new JPanel();
JPanel jPaneld = new JPanel();
jPanel.setLayout(new GridLayout(0, 1, 4, 0));
jPanela.setLayout(new FlowLayout(FlowLayout.RIGHT));
jPanelb.setLayout(new FlowLayout(FlowLayout.RIGHT));
jPanelc.setLayout(new FlowLayout(FlowLayout.RIGHT));
jPaneld.setLayout(new FlowLayout(FlowLayout.RIGHT));
jPanela.add(jLabel1);
jPanela.add(find);
jPanela.add(find_next);
jPaneld.add(matchcase);
jPanelb.add(jLabel2);
jPanelb.add(replacewith);
jPanelb.add(replace);
jPanelc.add(cancel);
//jPanelb.add(replaceAll);
find.setColumns(14);
replacewith.setColumns(14);
jPanel.setBorder(BorderFactory.createTitledBorder(""));
jPanel.add(jPanela);
jPanel.add(jPanelb);
jPanel.add(jPanelc);
jPanel.add(jPaneld);
getContentPane().add(jPanel);
find_next.addActionListener(this);
replace.addActionListener(this);
//replaceAll.addActionListener(this);
cancel.addActionListener(this);
setResizable(false);
setVisible(true);
pack();
// disable awt compatibility for find text field so that the enter key will work for default button
KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
Keymap map = find.getKeymap();
map.removeKeyStrokeBinding(enter);
getRootPane().setDefaultButton(find_next);
}
public void actionPerformed(ActionEvent se)
{

if (se.getSource() == cancel)
{
setVisible(false);
}
else if (se.getSource() == find_next)
{
finds();
}

else if (se.getSource() == replace)
{

Replace();
}
/* else if (se.getSource() == replaceAll)
{
replaceAll();
}*/
}
public void finds()
{
String str;
String txt;

if (matchcase.isSelected())
{
txt = Notepad.textArea.getText();
str = find.getText();
}
else
{
txt = Notepad.textArea.getText().toLowerCase();
str = find.getText().toLowerCase();
}
pos = txt.indexOf(str,Notepad.textArea.getSelectionEnd());
if (pos >=0)
Notepad.textArea.select(pos,(pos+str.length()));

}

/* String str;
String txt;

if (matchcase.isSelected())
{
txt = mynote.textArea.getText();
str = find.getText();
}
else
{
txt = mynote.textArea.getText().toLowerCase();
str = find.getText().toLowerCase();
}

pos = txt.indexOf(str,mynote.textArea.getSelectionEnd());

if (pos >= 0 )
System.out.println(pos+str.length());
mynote.textArea.select(pos,pos+str.length()+1);

}*/

public void Replace()
{

int start = Notepad.textArea.getSelectionStart();
int end = Notepad.textArea.getSelectionEnd();
if (end > start)
{
Notepad.textArea.replaceSelection(replacewith.getText());
System.out.println(start+(replacewith.getText().length()));
Notepad.textArea.select(start, start + replacewith.getText().length());

finds();
}else
{
System.out.println("this is inside the else loop");
System.out.println(start+replacewith.getText().length());
}
}

/*public void Replace()
{

int start = mynote.textArea.getSelectionStart();
System.out.print("start position is :");
int end = mynote.textArea.getSelectionEnd();
if (end > start)
System.out.print(mynote.textArea.getSelectedText());

//System.out.print((start)+(replacewith.getText().length()));
mynote.textArea.select(start,start+replacewith.getText().length());
//finds();
}*/
public void replaceAll()
{
Notepad.textArea.select(0,0);
while (pos >= 0)
Replace();
}
}
}

SWING(Panel Change)

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class PanelChange extends JFrame implements ActionListener,MouseListener
{

JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JLabel label = new JLabel("This is label");
JButton but = new JButton("This is button");

public PanelChange()
{
panel1.add(label);
panel2.add(but);


but.addActionListener(this);
label.addMouseListener(this);

getContentPane().add(panel2);
}

public void mouseClicked(MouseEvent me)
{
if(me.getClickCount() == 1)
{
panel1.setVisible(false);
getContentPane().add(panel2);
panel2.setVisible(true);
}
}
public void mousePressed(MouseEvent me){}
public void mouseReleased(MouseEvent me){}
public void mouseEntered(MouseEvent me){}
public void mouseExited(MouseEvent me){}

public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == but)
{
panel2.setVisible(false);
getContentPane().add(panel1);
panel1.setVisible(true);
}
}

public static void main(String args[])
{
PanelChange pc = new PanelChange();
pc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pc.setSize(200,200);
pc.setVisible(true);
}


}

SWING(JTextField And JPanel)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ab extends JFrame implements MouseListener
{
JPanel jpanel;
JTextField jtf;
int x,y;
String str;
public ab()
{
jtf = new JTextField();
getContentPane().add(jtf,BorderLayout.SOUTH);
getContentPane().addMouseListener(this);
}
public static void main(String[] args)
{
JFrame.setDefaultLookAndFeelDecorated(true);
ab frame = new ab();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.setSize(300,300);
frame.setVisible(true);
}
public void paint(Graphics g)
{
super.paintComponents(g);
str = "X:"+x+" "+"Y:"+y;
jtf.setText(str);
}
public void mousePressed(MouseEvent me)
{}
public void mouseReleased(MouseEvent me)
{}
public void mouseEntered(MouseEvent me)
{}
public void mouseExited(MouseEvent me)
{}
public void mouseClicked(MouseEvent me)
{
x = me.getX();
y = me.getY();
repaint();
}
}

SWING(Move Label)

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class MoveLabel extends JFrame
{
JLabel label;
public MoveLabel()
{
label = new JLabel(new ImageIcon("copy.gif"));
label.setBounds(20,30,16,19);
label.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent ke)
{
if(ke.getKeyCode() == KeyEvent.VK_DOWN)
{
label.setLocation(label.getX(),label.getY()+1);
repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_UP)
{
label.setLocation(label.getX(),label.getY()-1);
repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_LEFT)
{
label.setLocation(label.getX()-1,label.getY());
repaint();
}
if(ke.getKeyCode() == KeyEvent.VK_RIGHT)
{
label.setLocation(label.getX()+1,label.getY());
repaint();
}
}
});
label.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
if(me.getClickCount() == 1)
{
boolean dd = label.isOptimizedDrawingEnabled();
boolean ff = label.requestFocusInWindow();
repaint();
}
}

});
JPanel p = new JPanel();
p.setPreferredSize(new Dimension(2000,1000));
p.setLayout(null);
p.add(label);
JScrollPane js = new JScrollPane(p);
getContentPane().add(js);
}
public static void main(String args[])
{
MoveLabel frame = new MoveLabel();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.setSize(300,300);
frame.setVisible(true);
}
}

SWING(Cells)

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class Cells1 extends JFrame
{
private DPanel pan = new DPanel();
private Network net = new Network(pan);

public Cells1()
{
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{
dispose();
System.exit(0);
}
});
setBounds(10,10,400,350);
setContentPane(pan);
setVisible(true);
}

public class DPanel extends JPanel
{
private Graphics2D g2f;
private Color colors[] = new Color[]
{
Color.red,Color.black,Color.yellow,Color.blue,Color.green,Color.gray,Color.cyan,Color.cyan,Color.orange,Color.magenta
};
public DPanel()
{
setBackground(Color.white);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g2f = (Graphics2D)g;
Vector cells = net.getCells();
for (int j=0; j < cells.size(); j++)
draw((Cell_Info)cells.get(j));

g2f = null;
}
public void draw(Cell_Info ci)
{
if (g2f == null)
g2f = (Graphics2D)getGraphics();

Point p = ci.getPoint();
g2f.setColor(colors[ci.getAction()]);
g2f.fillOval(p.x,p.y,8,8);
}
}
public class Network extends Object
{
private Vector cells = new Vector();
public Network(final DPanel pan)
{
cells.add(new Cell_Info(20,20));
cells.add(new Cell_Info(50,120));
cells.add(new Cell_Info(45,20));
cells.add(new Cell_Info(90,55));
cells.add(new Cell_Info(40,110));
cells.add(new Cell_Info(35,80));
cells.add(new Cell_Info(95,70));
cells.add(new Cell_Info(24,40));
cells.add(new Cell_Info(35,60));
cells.add(new Cell_Info(80,100));
cells.add(new Cell_Info(90,90));
javax.swing.Timer ta = new javax.swing.Timer(200, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int v = (int)(Math.random()*cells.size());
int c = (int)(Math.random()*10);
Cell_Info ci = (Cell_Info)cells.get(v);
ci.setAction(c);
pan.draw(ci);
}
});
ta.start();
}
public Vector getCells()
{
return(cells);
}
}
public class Cell_Info extends Object
{
Point point;
int activ = 0;
public Cell_Info(int x, int y)
{
point = new Point(x,y);
}
public Point getPoint()
{
return(point);
}
public int getAction()
{
return(activ);
}
public void setAction(int a)
{
activ = a;
}
}
public static void main (String[] args)
{
new Cells1();
}
}

SWING(Focus)

import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;

public class FocusTest extends JFrame implements KeyListener
{
JTextField jtf1,jtf2,jtf3;
JPanel p;

public FocusTest()
{
jtf1 = new JTextField(10);
jtf2 = new JTextField(10);
jtf3 = new JTextField(10);

jtf1.addKeyListener(this);

p = new JPanel();
p.add(jtf1);
p.add(jtf2);
p.add(jtf3);

getContentPane().add(p);
}
public static void main(String dd[])
{
FocusTest ft = new FocusTest();
ft.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ft.setSize(200,200);
ft.setVisible(true);
}
public void keyPressed(KeyEvent ke)
{
if(ke.getKeyCode() == KeyEvent.VK_ENTER)
{
System.out.println("ll");
jtf3.requestFocus();
}
}
public void keyReleased(KeyEvent ke)
{}
public void keyTyped(KeyEvent ke)
{}
}

SWING(Menu Layout)

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


/* MenuLayoutDemo.java requires no other files. */

public class MenuLayoutDemo {
public JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
menuBar.setLayout(new BoxLayout(menuBar, BoxLayout.PAGE_AXIS));
menuBar.add(createMenu("Menu 1"));
menuBar.add(createMenu("Menu 2"));
menuBar.add(createMenu("Menu 3"));

menuBar.setBorder(BorderFactory.createMatteBorder(0,0,0,1,
Color.BLACK));
return menuBar;
}

// used by createMenuBar
public JMenu createMenu(String title) {
JMenu m = new HorizontalMenu(title);
m.add("Menu item #1 in " + title);
m.add("Menu item #2 in " + title);
m.add("Menu item #3 in " + title);

JMenu submenu = new HorizontalMenu("Submenu");
submenu.add("Submenu item #1");
submenu.add("Submenu item #2");
m.add(submenu);

return m;
}

/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("MenuLayoutDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and set up the content pane.
MenuLayoutDemo demo = new MenuLayoutDemo();
Container contentPane = frame.getContentPane();
contentPane.setBackground(Color.WHITE); //contrasting bg
contentPane.add(demo.createMenuBar(),
BorderLayout.LINE_START);

//Display the window.
frame.setSize(300, 150);
frame.setVisible(true);
}

public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application~s GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

class HorizontalMenu extends JMenu {
HorizontalMenu(String label) {
super(label);
JPopupMenu pm = getPopupMenu();
pm.setLayout(new BoxLayout(pm, BoxLayout.LINE_AXIS));
}

public Dimension getMinimumSize() {
return getPreferredSize();
}

public Dimension getMaximumSize() {
return getPreferredSize();
}

public void setPopupMenuVisible(boolean b) {
boolean isVisible = isPopupMenuVisible();
if (b != isVisible) {
if ((b==true) && isShowing()) {
//Set location of popupMenu (pulldown or pullright).
//Perhaps this should be dictated by L&F.
int x = 0;
int y = 0;
Container parent = getParent();
if (parent instanceof JPopupMenu) {
x = 0;
y = getHeight();
} else {
x = getWidth();
y = 0;
}
getPopupMenu().show(this, x, y);
} else {
getPopupMenu().setVisible(false);
}
}
}
}
}

SWING(Html Parse)

import java.io.*;
import java.net.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;

public class HtmlParseDemo {
public static void main(String [] args) {
Reader r;
if (args.length == 0) {
System.err.println("Usage: java HTMLParseDemo [url | file]");
System.exit(0);
}
String spec = args[0];
try {
if (spec.indexOf("://") > 0) {
URL u = new URL(spec);
Object content = u.getContent();
if (content instanceof InputStream) {
r = new InputStreamReader((InputStream)content);
}
else if (content instanceof Reader) {
r = (Reader)content;
}
else {
throw new Exception("Bad URL content type.");
}
}
else {
r = new FileReader(spec);
}

HTMLEditorKit.Parser parser;
System.out.println("About to parse " + spec);
parser = new ParserDelegator();
parser.parse(r, new HTMLParseLister(), true);
r.close();
}
catch (Exception e) {
System.err.println("Error: " + e);
e.printStackTrace(System.err);
}
}
}

/**
* HTML parsing proceeds by calling a callback for
* each and every piece of the HTML document. This
* simple callback class simply prints an indented
* structural listing of the HTML data.
*/
class HTMLParseLister extends HTMLEditorKit.ParserCallback
{
int indentSize = 0;

protected void indent() {
indentSize += 3;
}
protected void unIndent() {
indentSize -= 3; if (indentSize < indentsize =" 0;" i =" 0;">, " +
a.getAttributeCount() + " attrs)");
indent();
}

public void handleEndTag(HTML.Tag t, int pos) {
unIndent();
pIndent();
System.out.println("Tag end()");
}

public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) {
pIndent();
System.out.println("Tag(<" + t.toString() + ">, " +
a.getAttributeCount() + " attrs)");
}

public void handleError(String errorMsg, int pos){
System.out.println("Parsing error: " + errorMsg + " at " + pos);
}
}


Run the pragram

java HtmlParseDemo http://www.google.com

SWING(Html Display)

import java.awt.*;
import java.net.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;


public class HtmlDisplay extends JFrame implements HyperlinkListener
{
public static void main(String[] args)
{

HtmlDisplay obj=new HtmlDisplay();
obj.setSize(400,500);
obj.setVisible(true);
}
URL url;
JEditorPane html;
Document doc;
public HtmlDisplay()
{
try{

UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
url=new URL("http://202.71.136.142:8080");
html=new JEditorPane();
System.out.println("Editor created");
html.setEditable(false);
html.setPage(url);
html.addHyperlinkListener(this);
// JScrollPane scroller = new JScrollPane();
// JViewport vp = scroller.getViewport();
// vp.add(html);
// vp.setBackingStoreEnabled(true);

System.out.println("html created");
// getContentPane().add(scroller);
getContentPane().add(html);

}catch(Exception e){e.printStackTrace();}

}
public void hyperlinkUpdate(HyperlinkEvent e) {
try{

if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED)
{

doc = html.getDocument();
System.out.println(e.getURL());
html.setPage(e.getURL());
getToolkit().beep();
System.out.println("Listening");
}

}catch(Exception ex){
// html.setDocument(doc);
ex.printStackTrace();
}
}


}