Making a JLabel with selectable text

A Java JLabel works pretty well, but anyone who has used them is well aware that the user cannot select the text inside of them for copying and pasting. For certain applications, such as applications that display checksums, this can make manually copying the text quite tedious.
Here we will make something that looks and acts like a JLabel, but with fully selectable text. The 'trick' is that in actuality, the component is a JTextField, but we have modified its appearance to imitate a JLabel:

import java.awt.*;
import javax.swing.*;

public class SelectableLabel extends JTextField {
	
    public KlangLabel(String lblText) {
        super(lblText);
        this.setBorder(null);
        this.setOpaque(false);
        this.setEditable(false); 
        FontMetrics fm = this.getFontMetrics(this.getFont());
    	int height = fm.getHeight();
	//this is needed to make some layouts work properly
	this.setMaximumSize(new java.awt.Dimension(10000, height + 6));
	this.setPreferredSize(new java.awt.Dimension(0, height + 6));
	//have to call it here manually to force a possible resize
	this.setText(lblText);
    }

This works pretty well, but if the JLabel text is changed, we need to make some changes to make the textfield resize appropriately. So we'll overwrite that method:

    public void setText(String text) {
        super.setText(text);
	this.setCaretPosition(0);
	FontMetrics fm = this.getFontMetrics(this.getFont());
	int height = fm.getHeight();
	int width = fm.stringWidth(text) + 2;
	this.setPreferredSize( new Dimension(width + 2, height + 6));
    }

A more robust implementation might add other niceties, such as adjustments when setting font, etc.

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.