to limit number of chracters in textarea.
hello all,
please find below a small program to demonstrate how to limit number of charcaters in a textarea.
i searchedthe forum and i actually got the technique from the forum. but when i put together a sa program it does not work.
could anyone point out what is the problem in the small piece of code below.
i am working on jdk 1.2.1
thanx to all.
// Example illustrating Limiting number of characters in text area.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class try1 extends JApplet {
Container contentPane;
JLabel label;
JTA1 textarea;
public void init() {
// Get the handle on the applet's content pane.
contentPane = this.getContentPane();
// Create a text field and add a key listener to it.
textarea = new JTA1(25); // of 25 char width
// Create a button object and register an action listener
Button button = new Button("Clear");
button.addActionListener(new ButtonListener());
// Create a label with the titled border.
label = new JLabel("Key Typed: NiL");
label.setBorder(BorderFactory.createTitledBorder
("You pressed the Following Key"));
// Add the text field and button to the applet's content pane.
contentPane.setLayout(new BorderLayout());
contentPane.add("North", textarea);
contentPane.add(label);
contentPane.add("South", button);
// Get focus on text field.Note: You can do this only after you add the text field to the container
}
class ButtonListener implements ActionListener {// Create the button listener class.
public void actionPerformed(ActionEvent e) {
// Reset the text components
textarea.setText("");
//Return the focus to the text field.
}}}
class JTA1 extends JTextArea
{
private int limit;
public JTA1 ( int limit )
{
this.limit = limit;
addKeyListener( new LimitListener() );
}
class LimitListener extends KeyAdapter
{
public void keyPressed( KeyEvent ke )
{
if( getText().trim().length() >= limit )
{ke.consume(); //just consume KeyEvent
}
}
}
}

