Reputation: 59
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?
Upvotes: 1
Views: 488
Reputation: 1
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.
Upvotes: 0
Reputation: 389
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();
}
}
Upvotes: 1