1

I wont to display some text with Java Swing. It should also be possible to select it with the mouse in order to copy it. If I use a JLable it is not possible to select the text. If I use a JTextField or JTextArea it is possible to select and copy the text, but then the user can modify the text. Sure I can disable them so that it is not longer possible to change the text, but then again it is also not possible to select and copy the text ether. Is there some way to achieve what I am searching for?

2 Answers 2

1

Use setEditable(false) on a JTextField. Oddly, then, the mouse pointer is an arrow, but you can still select the text.

This worked for me:

import javax.swing.*;

public class TestTextField extends JFrame {
    private JTextField txt;

    public TestTextField() {
        txt = new JTextField("test");
        this.add(txt);
        txt.setEditable(false);
        this.setSize(200, 100);
    }
    
    public static void main(String[] asArgs) {
        new TestTextField().show();
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can set editable to false on a JTextField.

JTextField text = new JTextField();
text.setEditable(false);

Add this to hide the caret, it's the simplest way I could find.

class BlankCaret extends DefaultCaret { @Override public void paint(Graphics g) {/* Paint no caret. */}}
BlankCaret blankCaret = new BlankCaret();
text.setCaret(blankCaret);

It just extends the default caret and removes its paint method.

You can also try text.getCaret.setVisible(false); but I didn't have any luck with that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.