Warning: strpos(): needle is not a string or an integer in /home/thebestp/public_html/buildingblocksjava/wp-content/plugins/textlinkads/textlinkads.php on line 175

Warning: strpos(): needle is not a string or an integer in /home/thebestp/public_html/buildingblocksjava/wp-content/plugins/textlinkads/textlinkads.php on line 175

Warning: strpos(): needle is not a string or an integer in /home/thebestp/public_html/buildingblocksjava/wp-content/plugins/textlinkads/textlinkads.php on line 175
Keyboard Input: TypeWriter | Building Blocks Java

Keyboard Input: TypeWriter

Here’s a simple applet that uses the keyDown method to let you type some text.

import java.applet.Applet;
import java.awt.Event;
import java.awt.Graphics;

public class typewriter extends Applet {

int numcols = 80;
int numrows = 25;
int row = 0;
int col = 0;
char page[][] = new char[numrows][];

public void init() {

for (int i = 0; i < numrows; i++) {
page[i] = new char[numcols];
}
for (int i = 0; i < numrows; i++) {
for (int j = 0; j < numcols; j++) {
page[i][j] = '\0';
}
}

}

public boolean keyDown(Event e, int key) {

char c = (char) key;

switch (key) {
case Event.HOME:
row = 0;
col = 0;
break;
case Event.END:
row = numrows-1;
col = numcols-1;
break;
case Event.UP:
if (row > 0) row–;
break;
case Event.DOWN:
if (row < numrows-1) row++;
break;
case Event.LEFT:
if (col > 0) col–;
else if (col == 0 && row > 0) {
row–;
col=numcols-1;
}
break;
case Event.RIGHT:
if (col < numcols-1) col++;
else if (col == numcols-1 && row < numrows-1) {
row++;
col=0;
}
break;
default:
if (c == '\n' || c == '\r') {
row++;
col = 0;
}
else if (row < numrows) {
if (col >= numcols) {
col = 0;
row++;
}
page[row][col] = c;
col++;
}
else { // row >= numrows
col++;
}
}
repaint();
return true;
}

public void paint(Graphics g) {

for (int i=0; i < numrows; i++) {
String tempString = new String(page[i]);
g.drawString(tempString, 5, 15*(i+1));
}

}

}

Comments are closed.