|
| 1 | +package ui; |
| 2 | + |
| 3 | +import java.awt.event.KeyEvent; |
| 4 | + |
| 5 | +import paintcomponents.TextPaintComponent; |
| 6 | + |
| 7 | +public class KeyHandler { |
| 8 | + |
| 9 | + private PaintPanel paintPanel; |
| 10 | + private String pendingCommand; |
| 11 | + private boolean inCommandMode; |
| 12 | + private TextPaintComponent component; |
| 13 | + |
| 14 | + public KeyHandler(PaintPanel paintPanel) { |
| 15 | + pendingCommand = ""; |
| 16 | + this.paintPanel = paintPanel; |
| 17 | + this.component = new TextPaintComponent("", 0, 0); |
| 18 | + this.paintPanel.addPaintComponent(this.component); |
| 19 | + inCommandMode = false; |
| 20 | + } |
| 21 | + |
| 22 | + public void keyPressed(KeyEvent e) { |
| 23 | + |
| 24 | + // backspace |
| 25 | + if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE && inCommandMode) { |
| 26 | + if (pendingCommand.length() != 0) { |
| 27 | + pendingCommand = pendingCommand.substring(0, |
| 28 | + pendingCommand.length() - 1); |
| 29 | + } else { |
| 30 | + inCommandMode = false; |
| 31 | + } |
| 32 | + |
| 33 | + } else if (e.getKeyCode() == KeyEvent.VK_ENTER && inCommandMode) { |
| 34 | + |
| 35 | + executeCommand(pendingCommand); |
| 36 | + pendingCommand = ""; |
| 37 | + inCommandMode = false; |
| 38 | + } else { |
| 39 | + |
| 40 | + char keyChar = e.getKeyChar(); |
| 41 | + |
| 42 | + if (keyChar == ':') { |
| 43 | + pendingCommand = ""; |
| 44 | + inCommandMode = true; |
| 45 | + } else if (e.getKeyChar() != KeyEvent.CHAR_UNDEFINED |
| 46 | + && inCommandMode)/* if(e.isActionKey()) */{ |
| 47 | + pendingCommand += e.getKeyChar(); |
| 48 | + } |
| 49 | + |
| 50 | + } |
| 51 | + |
| 52 | + update(); |
| 53 | + |
| 54 | + } |
| 55 | + |
| 56 | + private void executeCommand(String pendingCommand2) { |
| 57 | + |
| 58 | + } |
| 59 | + |
| 60 | + private void update() { |
| 61 | + if (inCommandMode) { |
| 62 | + component.setDisplayingText(": " + pendingCommand); |
| 63 | + |
| 64 | + } else { |
| 65 | + component.setDisplayingText(pendingCommand); |
| 66 | + } |
| 67 | + int height = paintPanel.getHeight(); |
| 68 | + int rowHeight = component.getRowHeight(); |
| 69 | + component.setX(0); |
| 70 | + component.setY(height - rowHeight); |
| 71 | + paintPanel.repaint(); |
| 72 | + } |
| 73 | + |
| 74 | +} |
0 commit comments