Java AWT: Button Events and Arrow Key Shape Movement

Classified in Computers

Written at on English with a size of 3.75 KB.

Button Click Action Events

import java.awt.*;

import java.awt.event.*;

public class ButtonClickActionEvents

{

public static void main(String args[])

{

Frame f=new Frame("Button Event");

Label l=new Label("DETAILS OF PARENTS");

l.setFont(new Font("Calibri",Font.BOLD, 16));

Label nl=new Label();

Label dl=new Label();

Label al=new Label();

l.setBounds(20,20,500,50);

nl.setBounds(20,110,500,30);

dl.setBounds(20,150,500,30);

al.setBounds(20,190,500,30);

Button mb=new Button("Mother");

mb.setBounds(20,70,50,30);

mb.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent e)

{

nl.setText("NAME: " + "Aishwarya");

dl.setText("DESIGNATION: " + "Professor");

al.setText("AGE: " + "42");

}

});

Button fb=new Button("Father");

fb.setBounds(80,70,50,30);

fb.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent e)

{

nl.setText("NAME: " + "Ram");

dl.setText("DESIGNATION: " + "Manager");

al.setText("AGE: " + "44");

}

});

f.add(mb);

f.add(fb);

f.add(l);

f.add(nl);

f.add(dl);

f.add(al);

f.setSize(250,250);

f.setLayout(null);

f.setVisible(true);

}

}

Arrow Key Shape Movement

Write a program to move different shapes according to the arrow key pressed.

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

/*<applet code="ArrowKeys" Width=400 height=400></applet>*/

public class ArrowKeys extends Applet implements KeyListener

{

int x1=100,y1=50,x2=250,y2=200;

public void init()

{

addKeyListener(this);

}

public void keyPressed(KeyEvent ke)

{

showStatus("KeyDown");

int key=ke.getKeyCode();

switch(key)

{

case KeyEvent.VK_LEFT : x1=x1-10;

x2=x2-10;

break;

case KeyEvent.VK_RIGHT : x1=x1+10;

x2=x2+10;

break;

case KeyEvent.VK_UP : y1=y1-10;

y2=y2-10;

break;

case KeyEvent.VK_DOWN : y1= y1+10;

y2= y2+10;

break;

}

repaint();

}

public void keyReleased(KeyEvent ke)

{

}

public void keyTyped(KeyEvent ke)

{

repaint();

}

public void paint(Graphics g)

{

g.drawLine(x1,y1,x2,y2);

g.drawRect(x1,y1+160,100,50);

g.drawOval(x1, y1+235, 100, 50);

}

}

Entradas relacionadas: