Making a JLabel with selectable text
Submitted by jhallida on Thu, 04/15/2010 - 22:07
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:
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.