/* simulates a text editor, you can click the mouse anywhere and start typing * from there -- even over old characters */ import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Typewriter { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setTitle("Typewriter Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); TypePanel panel = new TypePanel(); panel.setFocusable(true); // needed for KeyListener to work frame.add(panel); frame.setSize(310, 310); frame.setVisible(true); } // the TypePanel will extend JPanel so we can use the Graphics class and will // implement MouseListener to move the cursor when the mouse is clicked and // KeyListener so that the user can type private static class TypePanel extends JPanel implements MouseListener, KeyListener { private int x, y; // the cooridnate of the cursor private char key; // the most recent key entered public TypePanel() { addMouseListener(this); // add the listeners addKeyListener(this); x = 10; // initialize the cursor position y = 20; key = ' '; // initialize the key to be printed } public void mouseClicked(MouseEvent e) // upon mouse click, move cursor { int tempX = e.getX(); int tempY = e.getY(); // make sure cursor is within margins if(tempX > 10 && tempX < 280 && tempY > 10 && tempY < 280) { x = tempX; y = tempY; } } public void keyTyped(KeyEvent e) // on key press, place the key in the panel at the cursor { // position and then move the cursor 7 to the right, but first key = e.getKeyChar(); // first save the cursor's old position to erase the cursor (triangle) repaint(); } public void paintComponent(Graphics g) { String temp = "" + key; // convert key into String for drawString g.setColor(Color.black); // draw the key as a String g.drawString(temp, x, y-1); x+=7; if(x>280) { x=10; y+=12; if(y>280) y=10; } } public void mouseEntered(MouseEvent e) {} // the remainder of the methods public void mouseExited(MouseEvent e) {} // needed to implement MouseListener public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void keyPressed(KeyEvent e) {} // and KeyListener public void keyReleased(KeyEvent e) {} } }