Evelyn R
2010-12-21 10:30:02 UTC
but clicking the keys does nothing? why?
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.*;
public class KeyBoardTest extends JApplet implements KeyListener, ActionListener
{
private String event = " "; // description of keyboard event
private int xcoordinate = 400; // starting xcoordinate of the message
private int ycoordinate = 300; // starting ycoordinate of the event
private int increment = 20; // int to increment location upon keyboard events
private JButton topButton; // button to reset location to the top
private JButton centerButton; // button to reset location to the center
@Override
public void init() // set up GUI
{
setLayout(new FlowLayout()); // set the layout of the applet
setSize(800, 600); // set the size of the applet
addKeyListener(this); // listen for keyboard events
centerButton = new JButton("Reset to Center :"); // set up Center button
centerButton.addActionListener(this);
add(centerButton);
topButton = new JButton("Reset to Top Left :"); // set up Top Left button
topButton.addActionListener(this);
add(topButton);
event = "You are at (" + xcoordinate + ", " + ycoordinate + ") ";
}
@Override
public void paint(Graphics g)
{
super.paint(g);
g.drawString(event, xcoordinate, ycoordinate); // draw messgae to the applet
}
public void keyPressed(KeyEvent e) // handle key presses
{
}
public void keyReleased(KeyEvent e) // handle key releases
{
}
public void keyTyped(KeyEvent e) // handle typing on applet
{
if (e.getKeyChar() == 'h') // when 'h' key is pressed
{
ycoordinate = ycoordinate + increment;
}
if (e.getKeyChar() == 'j') // when 'j' key is pressed
{
ycoordinate = ycoordinate - increment;
}
if (e.getKeyChar() == 'k') // when 'k' key is pressed
{
xcoordinate = xcoordinate - increment;
}
if (e.getKeyChar() == 'l') // when 'l' key is pressed
{
xcoordinate = xcoordinate + increment;
}
event = "You are at (" + xcoordinate + ", " + ycoordinate + ") ";
repaint();
}
public void actionPerformed(ActionEvent e) // handle button clicks
{
if(e.getSource() == topButton) // process clicking "Center" button
{
xcoordinate = 10; // reset the xcoordinate
ycoordinate = 50; // reset the ycoordinate
}
if(e.getSource() == centerButton) // process clicking "Clear" button
{
xcoordinate = 400; // reset the xcoordinate
ycoordinate = 300; // reset the ycoordinate
}
event = "You are at (" + xcoordinate + ", " + ycoordinate + ") ";
requestFocus();
repaint();
}
}