1

I am trying to create a TextArea using java that contains text that cannot be deleted/updated. That being said, the user can still add to the TextArea and delete their own text.

I've tried to play around with getting the length of the TextArea and listening for the 'backspace' keypress however I can still select all the text in the TextArea and replace it.

Example Code (TA is the TextArea)

TA.setText(cmdx);
cmdLength = TA.getDocument().getLength();

TA.getKeymap().addActionForKeyStroke(
        KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, 0), new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                TA.disable();
                try {
                    backSpace();
                } catch (BadLocationException ex) {
                    Logger.getLogger(CmdFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });

AND

public void backSpace() throws BadLocationException {
    System.out.println("Backspace is pressed");
    int currentLength = TA.getDocument().getLength();

    if(currentLength > cmdLength)
    {
        Document doc = TA.getDocument();
        doc.remove(doc.getLength() - 1, 1);
        TA.enable();
    }
}

I apologize if this question has already been asked.

Thank you in Advance!

osbt
  • 131
  • 5
  • 12
  • 1
    If I understand your question correctly. You always want a text that is seen in TextArea. In that case a) First populate text area with sticky b) disable backspace as you have done already c) When user types something, you update the text area with "user text"+ "sticky", there is no need for backSpace() method then - just TA.disable() for backspace key events. If user wants to delete his/her own text they can use "delete" not backspace - I am assuming its ok. because "delete" is not disabled.Now when user selects all text and deletes you update the text with sticky. – SomeDude Dec 05 '15 at 17:56

1 Answers1

1

Don't let the user directly type in text but catch the respective event and manually set the text to the textField. Then you can implement a check (for example if the text is starting with your sticky text) and if not add it at the beginning again. If it does then simply add the typed key at the end of the text.
Look here for more solutions

Community
  • 1
  • 1
Raven
  • 2,951
  • 2
  • 26
  • 42