Hello all, I'm working on a simple self-chat program, which will eventually lead into a server/client chat program, but for now I am trying to learn the basics. When I run my applet, when I type something in the textarea, it shows up in the text field just fine, but when I backspace whatever is in the text area, it adds letters to what is displayed in the text field.

For example:

I type hello in the line provided;
now if i backspace i'll get this in the text field hellolleh.

this is the code I have: I'm wondering what I need to add so that the textarea will delete the characters, and not add them when I press backspace. Something with Keycode I'm assuming, just unaware of how to set this up.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;


public class AppletThree extends Applet implements ActionListener, TextListener {

    TextField tf;
    TextArea ta;

    Button b;



    public void init() {


        setLayout(new BorderLayout());

        tf = new TextField();
        add(tf, BorderLayout.NORTH);

        ta = new TextArea();
        add(ta, BorderLayout.CENTER);

       //tf.addActionListener(this);

        tf.addTextListener(this);

        b = new Button("Clear");
        add(b, BorderLayout.SOUTH);

        b.addActionListener(this);
    }

    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == b) {
            ta.setText("");
        } else {
            String temp = tf.getText();

            ta.append(temp + "\n");


            tf.setText("");

        }
    }
    public void textValueChanged(TextEvent te) {

        String temp = tf.getText();

        char c = temp.charAt(temp.length()-1);

        ta.append(""+c);



    }
}

Dani AI

Generated

The behavior is caused by relying on "the last character" of the TextField after Java has already applied the key. As pointed out, a TextListener fires after the component’s text is updated, so reading tf.getText().charAt(lastIndex) will give the new last character — not the key that was pressed. That makes backspace look like an insertion of the previously-last character.

Two simple, reliable approaches (both suggested in the thread) are:

  • Drop the TextListener and use an ActionListener on the TextField to append the final line to the TextArea when Enter is pressed (standard chat behavior). This avoids per-keystroke mirroring entirely.
  • If real-time mirroring is required, either copy the whole TextField text into the TextArea each change (easy but will replace any chat history), or maintain previous text and apply only the delta so deletions remove the previously-appended characters.

Example of the delta approach (keep a small state string and update append/remove accordingly):

// keep this as a field: 
private String prev = "";

// inside textValueChanged:
String cur = tf.getText();
if (cur.length() > prev.length()) {
    ta.append(cur.substring(prev.length())); // new chars
} else if (cur.length() < prev.length()) {
    int remove = prev.length() - cur.length();
    String all = ta.getText();
    if (all.length() >= remove) ta.setText(all.substring(0, all.length() - remove));
    else ta.setText("");
}
prev = cur;

Notes: avoid KeyListener for text components; for modern UIs prefer Swing (JTextField/JTextArea + DocumentListener) or JavaFX instead of applets. If the TextArea holds chat history, keep a separate preview area or track the preview start index so deletions only affect the current draft and not previous messages.

Recommended Answers

All 5 Replies

What was the idea behind your textValueChanged? When the text is changed your code then duplicates the last letter - that seems wrong.

probalby

1) you want to use

   a) ActionListener for TextField only, then remove TextListener from TextField (standard logics for Chat)

   b) both, then content inside public void textValueChanged(TextEvent te) { must to know if is there event fired from ActionListener or KeyTyped, e.g. by using boolean for creating String or Char

2) note use JApplet, JTextField, JTextArea, DocumentListener instead of TextListener, because you wrote an program on resoures valid in last milenium

, it was a practice problem I had worked on about a week ago in class, I'm trying to extend the program so I can practice and get better with Java (big novice). I'm figuring I need to use KeyListener, and KeyEvent or something, but I'm not exactly sure where I need to implement it. I know ill need something along the lines of public void KeyPressed(KeyEvent ke) etc: something like that, just not entirely sure how to get it to recognize that when I press backspace in the textfield, the textarea also gets backspaced.

I'm figuring I need to use KeyListener, and KeyEvent or something, but I'm not exactly sure where I need to implement it.

not don't to use KeyListener in AWT/Swing, nor for (J)TextComponents

You get that behaviour because you copy the last character in one field to the other - that's the last char of the text after Java has updated it from the keyboard, it's not the last key that was entered. So with "world" in the field, after a backspace the field contains "worl", then you copy the "l" from that.
Simplest solution is propbably just to copy the entire text each time, not to try to do incremental updating.

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.