views:

562

answers:

4

So I'm stumped. I, for some reason, seem to remember that Java does weird things when you try to add new lines to stuff... so I think that may be the problem here.

This code is not working how you'd expect it to:

public void displayText(KeyEvent k){
    txt = inputArea.getText();
    outputArea.setText(txt);
    if(k.getKeyCode() == 10) //return
     outputArea.setText(txt + "\n");
}

You can double-check to see if I have the getKeyCode() set to the right number, but I'm almost positive that that part is correct.

EDIT: Thanks; I forgot about those constants...

And unfortunately, it works - but not really. if(k.getKeyCode() == k.VK_ENTER) returns true (this is a fact), but "\n" does not create the newline.

EDIT (take two): Full code:

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

public class GUI extends JFrame implements KeyListener{
    private JFrame frame;
    private JTextField inputArea;
    private JTextArea outputArea;
    private String txt;

    public GUI(){
     frame = new JFrame("My Frame");
     inputArea = new JTextField(1);
     outputArea = new JTextArea(5,10);
     inputArea.addKeyListener(this);
     outputArea.setLineWrap(true);
     txt = "";

     frame.setLayout(new GridLayout(2,10));
     frame.add(inputArea);
     frame.add(outputArea);
     frame.setVisible(true);
     frame.pack();
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void keyPressed(KeyEvent k){}
    public void keyTyped(KeyEvent k){}

    public void keyReleased(KeyEvent k) {
     displayText(k);
    }

    public void displayText(KeyEvent k){
     txt = inputArea.getText();
     outputArea.setText(txt);
     if(k.getKeyCode() == KeyEvent.VK_ENTER)
      outputArea.append("\n");
      //outputArea.setText(txt + "\n");
    }
}

Then another class with the main:

public class Driver {
    public static void main(String[] args){ 
     GUI gui = new GUI();
    }
}

EDIT: Basically, I'm trying to emulate Google Wave's ability to send text before the user presses Enter.

A: 

I know there is a difference with new line characters between OS's out there. You could try

System.getProperty("line.separator")

to get the new line character for the specific os it is running on. Don't know if that will fix your problem or not.

jschoen
A: 

EDIT

I have created a quick piece of code to add a KeyListener onto a JTextArea and this works fine. You don't need to particularly watch for an Enter key being pressed. How is this different from the rest of your code? (If you could paste more of it, that would be helpful.) I sort of feel like your KeyListener is not doing something properly. Are letters typing when you type? Try just taking out the if statement where you check for ENTER and see if that helps.

public class TestGui {

    private JFrame frame;
    private JTextArea textArea;

    public TestGui() {
     frame = new JFrame();
     frame.setSize(200, 200);

     textArea = new JTextArea();
     textArea.setSize(200, 200);
     frame.add(textArea);

            // Notice that I don't do anything inside this listener.
            // It doesn't need to be here.
     textArea.addKeyListener(new KeyListener() {

      @Override
      public void keyPressed(KeyEvent e) {
      }

      @Override
      public void keyReleased(KeyEvent e) {
      }

      @Override
      public void keyTyped(KeyEvent e) {
      }

     });

     frame.setVisible(true);
    }

    public static void main(String[] args) {
     TestGui gui = new TestGui();
    }
}
JasCav
Unfortunately, it failed to work...I did a little debugging, and it gets into the if statement correctly, it's just that "\n" apparently doesn't add newlines. I recently had the same problem with JLabels, which ended up being solvable by throwing the whole thing into HTML tags, and using <br> for a line break. I think I'll try that out and see if it works...
Pandemic21
@Pandemic21 - Crummy that it didn't work. While your suggested solution may work, it definitely is not the right one. My guess is something else is going on. Can you paste more of the code so that I can take a look at what you're doing? (I'm trying it out myself right now, too.)
JasCav
@Pandemic21 - I updated my answer with a test case. This should work. I would like to see more of your solution if possible.
JasCav
I would love to, but it would take a few comments to get it all in, and I feel like I'd be wasting space <_<.If you give me your email at pandemic21{at}gmail{d0t}com I could send it to you...
Pandemic21
Ahhh... I didn't realize that the <code> fields were resizing. Nevermind; I can post it there.
Pandemic21
I guess I'm confused. I type into the bottom box and hit [Enter] and it posts into top box. I might be misunderstanding what you're trying to do. It appears to work.
JasCav
+3  A: 

EDIT: After I see your full code, your keylistener is working. The problem is: outputArea.setText(txt); who overwrites your linebreaks. Try something like this:

public void displayText(KeyEvent k){
    txt = inputArea.getText();
    char key = k.getKeyChar();
    if(key != KeyEvent.VK_ENTER)
        outputArea.append(Character.toString(k.getKeyChar()));
    else {
        // do something special, then add a linebreak
        outputArea.append("\n");
    }
}

ORIGINAL ANSWER: Try using getKeyChar() instead of getKeyCode(). See http://java.sun.com/j2se/1.5.0/docs/api/java/awt/event/KeyEvent.html for when to use what. Also, since you are just testing on enter, you probarly won't need to use a KeyListener. You can use a ActionListener on the input-field instead. See sample code for both ActionListener and KeyListener solutions below.

public class JTextAreaTest extends JFrame{
private JTextArea txaConsole;
private JTextField txtInput;
private JButton btnSubmit;

public JTextAreaTest(){
 SubmitListener submitListener = new SubmitListener();
 MyKeyListener myKeyListener = new MyKeyListener();

 txaConsole = new JTextArea(10,40);
 txtInput = new JTextField();
 txtInput.addActionListener(submitListener);
 //txtInput.addKeyListener(myKeyListener);
 btnSubmit = new JButton("Add");
 btnSubmit.addActionListener(submitListener);

 add(new JScrollPane(txaConsole), BorderLayout.NORTH);
 add(txtInput, BorderLayout.CENTER);
 add(btnSubmit, BorderLayout.EAST);


 setDefaultCloseOperation(EXIT_ON_CLOSE);
 pack();
 setVisible(true);
 txtInput.requestFocusInWindow();
}

private void addInputToConsole(){
 String input = txtInput.getText().trim();
 if(input.equals("")) return;

 txaConsole.append(input + "\n");
 txtInput.setText("");
}

// You don't need a keylistener to listen on enter-presses. Use a
// actionlistener instead, as shown below.
private class MyKeyListener extends KeyAdapter {
 @Override
 public void keyTyped(KeyEvent e) {
  if(e.getKeyChar() == KeyEvent.VK_ENTER)
   addInputToConsole();
 }
}

private class SubmitListener implements ActionListener{
 @Override
 public void actionPerformed(ActionEvent e) {
  addInputToConsole();
 }
}

public static void main(String[] args) {
 new JTextAreaTest();
}
}
Mads Mobæk
Rawr, *facepalm*.Thank you, I dunno how I missed that. However, that brings me back to my original problem: this sends keystrokes such as shift, alt, control, backspace, ect...Some of this can be easily solved (function: isActionKey()), but the others need to be individually eliminated... Got any ideas on how to make this easier? <_<
Pandemic21
+1 for the right answer. Pandemic, it might be a good idea to accept mobmad's answer as a thank you (particularly since it answered your original question).
JasCav
A: 

I'm not sure I understand what you are trying to do, all I know is that you are using the wrong approach. You should NOT be using a KeyListener.

From what I can see you want the contents of the output text area to be the same as the contents of the input area. If this is your requirement then you just use:

JTextArea input = new JTextArea(...);
JTextArea output = new JTextArea(...);
output.setDocument( input.getDocument() );

Or if you are trying to listen for all the changes to the input text area then you should be using a DocumentListener. The Swing tutorial has a section titled "How to Write a Document Listener" for more information.

camickr