- For individual users
- Instant access to solutions
- Ask your tech questions
- Start your 30-day Free Trial
Main Topics
Browse All Topics
Hi Experts,
This is a strange behavior of setCaretPosition( getDocument().getLength() ). This line locates in keylistener method "public void keyTyped( KeyEvent event )" of file AgentTextPane.java.
The codes attached below are to demo my problem. In order to get a feel quickly what the problem is. Follow the steps please:
1. Compile AgentTextPane.java and TextPaneDisplay.java and run TextPaneDisplay.
2. Type "teh" once and type some thing else after it, you will see the words after "teh"(which has been changed to "the") are in "red". (It should be in default style, gray in color)
3. Type "teh" again, then the words after second "teh" are back to default style(which is agent style, gray in color).
What I need is after a word comes out from spell-checking, its style should be changed(in this case, red in color). The rest of words typed after it stay with the default style( agent style, which is gray in color).
Currently, the problem is that the default style was not changed back when the spell checker was used for the first time. The default style was changed back when the checkSpelling was called the second time. It follows the pattern. The default style is only changed back on the even number calls.
If I comment out the line in keyTyped method, the problem is gone. But I do need this line of code to stay there.
Could you explain me why it behaves like this? What is the better way to replace the same feature? (which to keep caret at the end of document all the time). Thanks!
[1] AgentTextPane.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class AgentTextPane extends JTextPane implements KeyListener{
/** The stopping point of the last word break */
private int stop = -1;
/** The style for agent */
private Style agentStyle = getTextStyle("AgentStyle",
/** The styled document agent uses */
private StyledDocument agentDoc;
public AgentTextPane( StyledDocument doc ){
super(doc);
//Get the document from text pane
agentDoc = (StyledDocument)getDocumen
//Sets the logical style for agent to use from the beginning position
agentDoc.setLogicalStyle(0
addKeyListener( this );
}
// --------------------------
// METHODS FOR THE KEYLISTENER INTERFACE
// --------------------------
public void keyPressed( KeyEvent event ){
switch( event.getKeyCode() )
{
case KeyEvent.VK_END:
setCaretPosition( getDocument().getLength() );
break;
case KeyEvent.VK_HOME:
setCaretPosition( 0 );
break;
default:
// Update stop point after hitting whitespace...
if( Character.isWhitespace(eve
checkSpelling();
break;
}
return;
}
public void keyTyped( KeyEvent event ){
if( event.getKeyChar() == '\b' && (getCaretPosition() - stop) <= 1 )
event.consume();
// If the caret isn't already at the end of the document, I need to
// put it there, because I do not want users to insert text into the
// middle of my document...
setCaretPosition( getDocument().getLength() ); //<----------this is the line causing the problem, take it out problem gone
return;
}
public void keyReleased( KeyEvent event ){
// EMPTY
}
/**
* Checks the spelling of the last inserted word.
*
*/
private void checkSpelling()
{
StyledDocument doc = (StyledDocument)getDocumen
// See if my stop value is out of sync with the document...
if( stop < 0 || stop >= doc.getLength() )
stop = 0;
// Retrieve the text to check and send it to the spell checker...
try{
String text = doc.getText(stop, doc.getLength() - stop).trim();
String replace = checkWord( text.trim() );
Style theStyle = getTextStyle("MyStyle", Color.red);
if(!replace.equals(text.tr
if( stop > 0 )
++stop;
// Remove the misspelled word and add in the replacement...
doc.remove( stop, doc.getLength() - stop );
doc.insertString( stop, replace, null );
// Change the color of the replacement text so it is
// clear that the word came from the spell-checker...
doc.setCharacterAttributes
}
}
catch( Exception ignored ){
}
stop = doc.getLength();
return;
}
// Set the style for the styled document in a JTextArea
private Style getTextStyle(String styleName, Color foregroundColor){
StyledDocument styleDoc = (StyledDocument)getDocumen
Style style;
// Set the style attributes for the doc
style = styleDoc.addStyle("AgentSt
// Bold
StyleConstants.setBold(sty
// Font family
StyleConstants.setFontFami
// Font size
StyleConstants.setFontSize
// Foreground color
StyleConstants.setForegrou
return style;
}
// Fake one for simulation
public String checkWord ( String word) {
String replacedWord;
String wrongStr1 = "teh";
String wrongStr2 = "experter";
String wrongStr3 = "exp";
if (word.equals(wrongStr1)){
replacedWord = "the";
}
else {
if (word.equals(wrongStr2))
replacedWord = "EXPERT";
else {
if(word.equals(wrongStr3))
replacedWord = "EXPERT";
else
replacedWord = word;
}
}
return replacedWord;
}
}
[2] TextPaneDisplay.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
public class TextPaneDisplay extends JFrame {
StyledDocument doc = new DefaultStyledDocument();
AgentTextPane agentArea = new AgentTextPane(doc);
public TextPaneDisplay() {
JScrollPane scrollingArea = new JScrollPane(agentArea);
scrollingArea.setBorder(Bo
// Get the content pane, set layout, add to center
Container content = this.getContentPane();
content.setLayout(new BorderLayout());
content.add(scrollingArea,
this.pack();
}
public static void main(String[] args) {
JFrame win = new TextPaneDisplay();
win.setTitle("AgentTextPan
win.setDefaultCloseOperati
win.setSize( 500, 400 );
win.setVisible(true);
}
}
This question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
Business Accounts
Answer for Membership