从JLabel中选择文本?

是否可以从JLabel中选择文本? 如果没有,那么使用什么是最好的替代控件,以及如何将其配置为像JLabel一样?

JTextField不允许像JLabel那样的html格式的文本。 如果你想要可选择的html文本,你可以尝试将JTextPane设置为html格式:

JTextPane f = new JTextPane(); f.setContentType("text/html"); // let the text pane know this is what you want f.setText("Hello World"); // showing off f.setEditable(false); // as before f.setBackground(null); // this is the same as a JLabel f.setBorder(null); // remove the border 

您可以在不启用编辑的情况下使用JTextField

 JTextField f=new JTextField("Hello World"); f.setEditable(false); content.add(f); 

皮埃尔

基于答案:您可以在不启用编辑的情况下使用JTextField

 JTextField f=new JTextField("Hello World"); f.setEditable(false); f.setBackground(null); //this is the same as a JLabel f.setBorder(null); //remove the border 

我不知道如何在选择文本时将文本从“跳转”中停止,或者替换文本(以编程方式)。 也许这只是我的电脑……

使用JTextField时,您还需要删除边框: f.setBorder(null);

并设置禁用的文本颜色: f.setDisabledTextColor(Color.black);

作为下面的变体,CopyableLabel支持html标签和Fonts作为JLabel。

 public class CopyableLabel extends JTextPane { private static final long serialVersionUID = -1; private static final Font DEFAULT_FONT; static { Font font = UIManager.getFont("Label.font"); DEFAULT_FONT = (font != null) ? font: new Font("Tahoma", Font.PLAIN, 11); } public CopyableLabel() { construct(); } private void construct() { setContentType("text/html"); setEditable(false); setBackground(null); setBorder(null); putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, true); setFont(DEFAULT_FONT); } } 

JLabels无法编辑。

但是,您可以使用JTextField并只更改前景/背景颜色,使其显示为JLabel。 如果你想真正想要你可以添加代码来改变颜色,当它被选中以表明它是可编辑的。