package org.javaforum.y06.june.jtextarea;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JTextArea;
/**
* @version $Revision: $, $Date: $
*/
public class TabTextArea extends JFrame implements KeyListener
{
/**
* string, which shall be inserted, when TABULATOR was pressed
*/
private static final String TABULATOR_STRING = " ";
/**
* JTextArea, to demonstrate the TABULATOR
*/
private JTextArea area;
/**
* Create new TABULATOR demonstrate
* @param args
*/
public static void main(String[] args)
{
new TabTextArea();
}
/**
* Initialise and show the frame
*/
public TabTextArea()
{
super("JTextAreaTest");
initComponents();
initFrame();
}
/**
* Init the components of frame
*/
private void initComponents()
{
/*
* create new textarea and register keylistener
*/
this.area = new JTextArea("TabTextArea", 10, 5);
this.area.addKeyListener(this);
// add texteare to frame
add(this.area);
}
/**
* initialises the frame
*/
private void initFrame()
{
pack();
validate();
setVisible(true);
}
/**
* (non-Javadoc)
* @see java.awt.event.KeyListener#keyPressed(java.awt.event.KeyEvent)
*/
public void keyPressed(KeyEvent e)
{
/**
* interrupt / consume the event, when the TABULATOR is pressed and
* insert the replacement string instead
*/
if (e.getKeyCode() == KeyEvent.VK_TAB)
{
e.consume();
int caretPosition = this.area.getCaretPosition();
this.area.insert(TABULATOR_STRING, caretPosition);
}
}
/**
* (non-Javadoc)
* @see java.awt.event.KeyListener#keyReleased(java.awt.event.KeyEvent)
*/
@SuppressWarnings("unused")
public void keyReleased(KeyEvent e)
{
// empty
}
/**
* (non-Javadoc)
* @see java.awt.event.KeyListener#keyTyped(java.awt.event.KeyEvent)
*/
@SuppressWarnings("unused")
public void keyTyped(KeyEvent e)
{
// empty
}
}