Hi I have created a chat window. This contains a JTextPane and a JTextArea. when i enter text in the JTextArea and press enter the text has to be displayed in the text pane and the JTextArea should be empty to take the next input.
Everything is working fine. When i enter text in the JTextArea and when i press enter the text is being displayed in the JTextPane but the cursor of the JTextArea is starting in the 2nd row of the JTextArea by default from the 2nd time which is causing unnecessary spacing in the JTextPane if I don't move the JTextArea cursor manually to the First row. How can i resolve this issue? The cursor by default should appear at the start of the JTextArea.
My code is as follows:-
package com.example.gui;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
public class ChatGui extends JFrame {
private static final long serialVersionUID = 4942132120249803370L;
private JTextPane ma;
private JTextArea ua;
public ChatGui(String title){
super(title);
JDesktopPane dp=new JDesktopPane();
dp.setLayout(null);
this.setContentPane(dp);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
ma=new JTextPane();
ma.setEditable(false);
JScrollPane jspma=new JScrollPane(ma);
jspma.setBounds(0, 0, 250, 300);
dp.add(jspma);
ua=new JTextArea();
ua.setToolTipText("Enter your message here...");
ua.setLineWrap(true);
ua.setWrapStyleWord(true);
ua.addKeyListener(new ChatGUIUAListener(this));
JScrollPane jspua=new JScrollPane(ua);
jspua.setBounds(0, 300, 250, 100);
dp.add(jspua);
this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
this.setSize(260, 450);
this.setVisible(true);
}
public JTextPane getMa() {
return ma;
}
public JTextArea getUa() {
return ua;
}
public static void main(String args[]){
ChatGui chat=new ChatGui("chat window..");
}
}
package com.example.gui;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JTextArea;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
public class ChatGUIUAListener extends KeyAdapter{
private ChatGui chatGui;
public ChatGUIUAListener(ChatGui chatGui){
this.chatGui=chatGui;
}
@Override
public void keyPressed(KeyEvent event) {
if(event.getKeyCode()==10){
JTextArea userArea=chatGui.getUa();
String messageTobeSent=userArea.getText();
userArea.setText("");
userArea.setCaretPosition(userArea.getDocument().getLength());
JTextPane mainArea=chatGui.getMa();
Document doc=mainArea.getDocument();
SimpleAttributeSet bold=new SimpleAttributeSet();
StyleConstants.setBold(bold, true);
try{
doc.insertString(doc.getLength(), messageTobeSent+"\n",null);
}catch(BadLocationException ble){
System.out.println(ble);
}
}
}
}