Hello all..
I have a problem with my program in here. I am making a chatting application and i just need a final touch. This is the code snippet i make to represent my problem. First, i'd like to tell that i want to make the sending process like the one in yahoo messenger. So i use TextArea for the sending object (to support multiline).
The output i desire is, each time i press enter, the text in txtArea will b sent to lblDisplay and each time i press Ctrl+Enter, the text in txtArea will have to move to the next line (just like in YM).
But, in here, each time i press enter, the cursor move to the second line instead to the first line (you can test the code) and that create one blank line each time i send to the messageArea in my chatting application. But if i use the button to send it (instead of enter), the cursor is normal (it's not moving to the second line). I duno how to manipulate that. And the other problem is that, the Ctrl+Enter is not working as i wish. Would anyone please give me a hand so that i can complete my project. It's still pending just because of this minute problem. Thank you very much in advance for any assistance given :) .

import java.awt.event.*;
import javax.swing.*;

public class TextAreaCtrlEnter extends JFrame implements KeyListener, ActionListener{

	JLabel lblDisplay;
	JTextArea txtArea;
	JButton btnSend;
	JPanel panelObject;

	public TextAreaCtrlEnter() {
		panelObject = new JPanel();
		getContentPane().add(panelObject);
		lblDisplay = new JLabel("");
		txtArea = new JTextArea(5,20);
		btnSend = new JButton("Send");
		panelObject.add(lblDisplay);
		panelObject.add(txtArea);
		panelObject.add(btnSend);
		setVisible(true);
		setSize(250,300);

		txtArea.addKeyListener(this);
		btnSend.addActionListener(this);

	}

	//KeyListener Interface
	public void keyTyped(KeyEvent e) {}
	public void keyReleased(KeyEvent e) {}
	public void keyPressed(KeyEvent e) {
		if (e.getSource() == txtArea) {
			if ((e.getKeyCode() == KeyEvent.VK_ALT) && (e.getKeyCode() == KeyEvent.VK_ENTER)) {
				txtArea.setText(txtArea.getText());
				txtArea.setText("\n");
			}
			if (e.getKeyCode() == KeyEvent.VK_ENTER) {
				lblDisplay.setText(txtArea.getText());
				txtArea.setText("");
				txtArea.requestFocus();
			}

		}
	}

	//ActionListener Interface
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == btnSend) {
			lblDisplay.setText(txtArea.getText());
			txtArea.setText("");
			txtArea.requestFocus();
		}
	}

	public static void main(String args[]) {
		TextAreaCtrlEnter obj = new TextAreaCtrlEnter();
	}
}

Recommended Answers

All 11 Replies

I don't know too much about KeyListeners, but

if ((e.getKeyCode() == KeyEvent.VK_ALT) && (e.getKeyCode() == KeyEvent.VK_ENTER)) {
				txtArea.setText(txtArea.getText());
				txtArea.setText("\n");
			}
			if (e.getKeyCode() == KeyEvent.VK_ENTER) {
				lblDisplay.setText(txtArea.getText());
				txtArea.setText("");
				txtArea.requestFocus();
			}

doesn't look like it could possibly work. If the first of those statements was true, then the second one would always be true as well. . and don't you only want one of those two things to be executed? You might want to read the Java Sun tutorial on KeyListeners. Furthermore, this statement txtArea.setText(txtArea.getText()); does nothing. You just got the text from txtArea, then set the text in txtArea to what it already was. Why? If I were you I'd check to make sure that the code inside those if statements is actually being reached.

I suggest taking a look at the InputEvent methods that are inherited by the KeyEvent class. One of them is "isControlDown()" look at that one. =)

Well, when i change this code

if ((e.getKeyCode() == KeyEvent.VK_ALT) && (e.getKeyCode() == KeyEvent.VK_ENTER)) {
				txtArea.setText(txtArea.getText());
				txtArea.setText("\n");
			}

into like this

if ((e.getKeyCode() == KeyEvent.VK_DOWN)) {
				//txtArea.setText(txtArea.getText());
				txtArea.append("\n");
			}

it function but when i send or click enter, it's not multiline and still each time i type enter, the cursor move to the second line of the textarea. why like that?
And i've tried about isControlDown(), but i think it won't work since we are comparing boolean and int. Any other way to solve this? coz i dun want to use DOWN key. I want to use Ctrl+Enter to move to next line and enter to display it without moving the cursor to second line in the textarea after entering.

I don't know about your second question, but the reason it is moving to the second line of the Text Area is because you are appending \n to the text area, which just adds a new line. If you wanted to set the text to something else, use the setText method. If you want to set the position of the cursor, I believe the setCaretPosition method will help you there. http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/JTextComponent.html#setCaretPosition(int)

Yes but the DOWN key only wil make it move to the next line. The ENTER key is not supposed to make it move to next line in the textarea right? My problem is that when i press ENTER, the text in textarea move to lblDisplay but the cursor in textarea moves to next line after ENTER. How can i fix that?

after you send the contents of the text area, set the contents to nothing (ie. JTextAreaObject.setText("");) Hope that clears some of it up

Yes but the DOWN key only wil make it move to the next line. The ENTER key is not supposed to make it move to next line in the textarea right? My problem is that when i press ENTER, the text in textarea move to lblDisplay but the cursor in textarea moves to next line after ENTER. How can i fix that?

I just told you. Use the setCaretPosition method. I'm pretty sure if you get the length of the text that is in the text field, then set the caret position to be at that length, then it will be sitting after the last character that the user typed. I've never used the method, but hey.. you're asking for solutions so try stuff out when it's suggested. The reason that typing enter is jumping down a line is pretty obvious. . that's what the enter key does.

Ok... i am working on it... thank you very much for the suggestions. :-)

Thank you very much for the input about caret position BestJewSinceJC. This is the final code and it's working. I hope it will be useful for anybody who bumps into the same problem.

import java.awt.event.*;
import javax.swing.*;

public class TextAreaCtrlEnter extends JFrame implements KeyListener, ActionListener{

	JLabel lblDisplay;
	JTextArea txtArea;
	JButton btnSend;
	JPanel panelObject;

	public TextAreaCtrlEnter() {
		panelObject = new JPanel();
		getContentPane().add(panelObject);
		lblDisplay = new JLabel("");
		txtArea = new JTextArea(5,20);
		btnSend = new JButton("Send");
		panelObject.add(lblDisplay);
		panelObject.add(txtArea);
		panelObject.add(btnSend);
		setVisible(true);
		setSize(250,300);

		txtArea.addKeyListener(this);
		btnSend.addActionListener(this);

	}

	//KeyListener Interface
	public void keyTyped(KeyEvent e) {}
	public void keyReleased(KeyEvent e) {}
	public void keyPressed(KeyEvent e) {
        if(e.getKeyCode() != 10){
            //
        }
        else{
            if(e.isControlDown() && e.getKeyCode() == 10){
                String strBefore = txtArea.getText();
                txtArea.setText(strBefore+"\n");
            }
            else{
                lblDisplay.setText(txtArea.getText());
                txtArea.setText("");
                int caretPosition = txtArea.getCaretPosition()-1;
                txtArea.setCaretPosition(caretPosition);
            }

        }
	}

	//ActionListener Interface
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == btnSend) {
			lblDisplay.setText(txtArea.getText());
			txtArea.setText("");
			txtArea.requestFocus();
		}
	}

	public static void main(String args[]) {
		TextAreaCtrlEnter obj = new TextAreaCtrlEnter();
	}
}

There might be some minor correction need to be made according to system u r making, but the main is running well.

2 things about that part:

if(e.isControlDown() && e.getKeyCode() == 10){
                String strBefore = txtArea.getText();
                txtArea.setText(strBefore+"\n");

1. Using Ascii numbers to check if key is pressed is not a nice way to check it - makes it unreadable without ascii char table in front of Your eyes. Instead use KeyEvent's constants :

if ( e.getKeyCode() == KeyEvent.VK_ENTER )

2. Getting a text from text area and then setting that text + smth is very slow and unoptimal operation. If You just wanna add some string at the end of text area, then use append method:

txtArea.append( "\n" );

If You had few hundred/tousand of lines in text area You would see a huge difference.

Thanks for the efficient input Zibo...i wil kep that in mind...;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.