Search code examples
javaswing

Java Swing: display Text selectable


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?


Solution

  • 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();
        }
    }