Re: JTextArea contraints
To: comp.lang.java.gui
jc_halsey@yahoo.com wrote:
I have tried and cont. to limit the rows(lines) on a JTextArea.
I have created a PlainDoc. and have successfully limited the max
char(s).
The max chars is good for the text area as a whole if you start at 0
and fill every line.
However in this case, which would be a text editor, a vertical limit is
needed.
The user can not exceed past row/line 17. As is now, the user can type
past line 17.
Any suggestions on how to limit?
This one's rough - needs a bucket-load of testing
import javax.swing.*;
import java.awt.*;
import javax.swing.text.*;
class Testing
{
JTextArea ta = new JTextArea();
final int MAX_LINES = 5;
int height;
public void buildGUI()
{
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
JScrollPane sp = new JScrollPane(ta);
sp.setPreferredSize(new Dimension(100,100));
JFrame f = new JFrame();
f.getContentPane().add(sp);
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
height =
ta.getGraphics().getFontMetrics().getHeight()*(MAX_LINES-1);
ta.setDocument(new PlainDocument(){
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException{
String oldText = ta.getText();
super.insertString(offs, str, a);
if(ta.modelToView(getLength()).y > height)
{
ta.setText(oldText);
java.awt.Toolkit.getDefaultToolkit().beep();
}
}
});
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new Testing().buildGUI();
}
});
}
}
---
* Synchronet * The Whitehouse BBS --- whitehouse.hulds.com --- check it out free usenet!
--- Synchronet 3.15a-Win32 NewsLink 1.92
Time Warp of the Future BBS - telnet://time.synchro.net:24