Text Typer
Instructions: 1. Click on the panel. 2.
Type text. 3. Press enter for new line. 4. Press Backspace
to delete text.
5. Press CTRL+R for Red text. 6. Press CTRL+G for Green text. 7.
Press CTRL+K for Black text.
8. Press CTRL+B for Bold text. 9. Press CTRL+P for Plain text. 10.
Press CTRL+I for Italic text.
Complete Source
Code
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TextTyper {
public static String[] sentence =
new String[15];
public static int index = 0;
public static Color color =
Color.BLACK;
public static Font font = new
Font("TimesRoman",Font.PLAIN,14);
public static class
TextTyperPanel extends
JPanel {
public void
paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(color);
g.setFont(font);
g.drawString(sentence[index] + "_",10,15*(index+1));
}
}
public static class
TextTyperListener implements
MouseListener,
KeyListener {
public void
mousePressed(MouseEvent e) {
TextTyperPanel source = (TextTyperPanel) e.getSource();
source.requestFocus();
}
public void
mouseReleased(MouseEvent e) {}
public void
mouseClicked(MouseEvent e) {}
public void
mouseEntered(MouseEvent e) {}
public void
mouseExited(MouseEvent e) {}
public void
keyPressed(KeyEvent e) {
TextTyperPanel source = (TextTyperPanel) e.getSource();
if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE && sentence[index].length() >
0) {
sentence[index] = sentence[index].substring(0,sentence[index].length()-1);
source.repaint(0,15*(index)+5,600,20);
}
if (e.getKeyCode() == KeyEvent.VK_ENTER && index < 14) {
index++;
source.repaint(0,15*(index)+5,600,20);
}
if (e.getKeyCode() == KeyEvent.VK_R && e.getModifiers() == 2) color =
Color.RED;
if (e.getKeyCode() == KeyEvent.VK_G && e.getModifiers() == 2) color =
Color.GREEN;
if (e.getKeyCode() == KeyEvent.VK_K && e.getModifiers() == 2) color =
Color.BLACK;
if (e.getKeyCode() == KeyEvent.VK_B && e.getModifiers() == 2) {
font = new Font("TimesRoman",Font.BOLD,14);
}
if (e.getKeyCode() == KeyEvent.VK_P && e.getModifiers() == 2) {
font = new Font("TimesRoman",Font.PLAIN,14);
}
if (e.getKeyCode() == KeyEvent.VK_I && e.getModifiers() == 2) {
font = new Font("TimesRoman",Font.ITALIC,14);
}
}
public void
keyReleased(KeyEvent e) {}
public void
keyTyped(KeyEvent e) {
TextTyperPanel source = (TextTyperPanel) e.getSource();
if (e.getKeyChar() != '\b' && sentence[index].length() < 70
&& e.getModifiers() != 2) {
sentence[index] += e.getKeyChar();
source.repaint(0,15*(index)+5,600,20);
}
}
}
public static void
main(String[] args) {
TextTyperListener
listener = new TextTyperListener();
TextTyperPanel
myPanel = new TextTyperPanel();
JFrame myFrame =
new JFrame("TextTyper");
myPanel.setBackground(Color.WHITE);
myPanel.addMouseListener(listener);
myPanel.addKeyListener(listener);
myFrame.add(myPanel);
myFrame.setSize(616,338);
myFrame.setLocation(100,100);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
for (int i = 0; i
< 15; i++) sentence[i] = "";
}
}
|