import javax.swing.*; import java.awt.*; import java.awt.event.*; public class EtchSketch { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setTitle("E-S Demo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); ESPanel panel = new ESPanel(); panel.setFocusable(true); // for the KeyListener to work, we have frame.add(panel); // to do this frame.setSize(300, 300); // set the size of the frame frame.setVisible(true); } private static class ESPanel extends JPanel implements KeyListener { private boolean setClear; // used to toggle whether to draw or erase screen private int x, y; // the cooridnate of the cursor private int direction; // the latest direction the user has specified // 0 = left, 1 = up, 2 = right, 3 = down public ESPanel() { addKeyListener(this); setClear = false; // do not erase unless user presses x = 150; // initialize the cursor position y = 150; direction = 0; // initialize the direction to left } public void keyPressed(KeyEvent e) { switch(e.getKeyCode()) // upon key press, if it is an arrow key, { // then set direction appropriately case KeyEvent.VK_LEFT: direction = 0; break; case KeyEvent.VK_UP: direction = 1; break; case KeyEvent.VK_RIGHT: direction = 2; break; case KeyEvent.VK_DOWN: direction = 3; break; case KeyEvent.VK_ENTER: { // if then toggle boolean so that setClear = true; // we can erase the screen break; } } repaint(); } // implement the rest of the KeyListener public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public void paintComponent(Graphics g) { if(setClear) // if the user wants to erase, then { // erase g and reset boolean super.paintComponent(g); setClear = false; } else // otherwise determine the direction and { // draw a 2-pixel line in that direction g.setColor(Color.black); // from the current position switch(direction) // and then extend x or y appropriately { // but stop at the "edge" of the screen (10 or 290) case 0 : g.drawLine(x, y, x-2, y); x-=2; if (x < 10) x = 10; break; case 1 : g.drawLine(x, y, x, y-2); y-=2; if (y < 10) y = 10; break; case 2 : g.drawLine(x, y, x+2, y); x+=2; if (x > 290) x = 290; break; case 3 : g.drawLine(x, y, x, y+2); y+=2; if (y > 290) y = 290; break; } } } } }