从JLabel中选择文本?

mel*_*lis 29 java swing

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

Are*_*end 30

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("<html>Hello World</html>"); // showing off
f.setEditable(false); // as before
f.setBackground(null); // this is the same as a JLabel
f.setBorder(null); // remove the border
Run Code Online (Sandbox Code Playgroud)

  • 这篇文章提供了一个有用的建议,以使字体与JLabel上通常显示的字体相匹配:https://explodingpixels.wordpress.com/2008/10/28/make-jeditorpane-use-the-system-font/ (3认同)

Pie*_*rre 14

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

JTextField f=new JTextField("Hello World");
f.setEditable(false);
content.add(f);
Run Code Online (Sandbox Code Playgroud)

皮埃尔


lin*_*fox 10

基于答案:您可以使用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
Run Code Online (Sandbox Code Playgroud)

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


akf*_*akf 7

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

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


小智 5

作为下面的变体,CopyableLabel 支持 html 标签和字体作为 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);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 1

JLabels 不可编辑。

但是,您可以使用 JTextField 并且只需更改前景色/背景色即可使其显示为 JLabel。如果您想要真正花哨,您可以添加代码来在选择它时更改颜色以表明它是可编辑的。