The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
November 2000

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

reset caret position to start of JTextPane on press of EnterKey

Posted by rajul on December 26, 2000 at 5:33 AM

Hi,
Iam using a JTextPane in a applet.On press of enter key, i need
to capture the typed text in the JTextPane,clear it and reposition
the cursor to the start of the JTextPane.However, the cursor is
going to the second line.could anybody tell me why and how do i
position it to the top.The code iam using is :
import javax.swing.*;
import javax.swing.JApplet;
import javax.swing.text.*;
import java.awt.event.*;
import java.awt.*;


public class testTextPane1 extends JApplet implements KeyListener
{


JTextPane messageArea;
DefaultStyledDocument doc1 = new DefaultStyledDocument();

JScrollPane scroll;

public void init()
{
Container pane=this.getContentPane();
JPanel con=new JPanel();

messageArea=new JTextPane(doc1);
messageArea.setBackground(Color.red);
messageArea.setCaretColor(Color.white);
scroll=new JScrollPane(messageArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
messageArea.addKeyListener(this);//addActionListener(this);
scroll.setMaximumSize(new Dimension(200,100));
scroll.setPreferredSize(new Dimension(100,40));
con.add(scroll);
pane.add(con);
}

public void keyPressed(KeyEvent aKe)
{
int key=aKe.getKeyCode();
System.out.println("code of key is "+key);
int pointerS1=0;
String te="";
try
{

pointerS1=messageArea.getCaretPosition();
System.out.println("caret position is "+pointerS1);
pointerS1=doc1.getLength();


}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("length of the string is "+ pointerS1+" and wht is vk-enter "+KeyEvent.VK_ENTER);


if (key==KeyEvent.VK_ENTER)
{

Document doc1=messageArea.getDocument();
if (pointerS1>0)
{

try
{
te=doc1.getText(0,pointerS1);
System.out.println("text is "+te);

}
catch(BadLocationException e)
{
}
}
try
{

doc1.remove(0,pointerS1);
doc1.createPosition(0);
messageArea.setCaretPosition(doc1.getLength());

}
catch(BadLocationException e)
{
e.printStackTrace();
}

System.out.println("position is this "+messageArea.getCaretPosition());
messageArea.requestFocus();
}
}




public void keyReleased(KeyEvent a)
{
}
public void keyTyped(KeyEvent aa)
{
}
}



Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us