如何在 JTextArea Swing 上禁用文本选择 [英] How to disable text selection on JTextArea Swing

查看:52
本文介绍了如何在 JTextArea Swing 上禁用文本选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不希望用户选择 JTextArea 上的内容.我使用 setEditable(false) 但它不起作用.如何禁用JTextArea 组件的此功能.你能给我建议吗.谢谢.

I don't want the user to select the content on JTextArea. I use setEditable(false) but it's not working. How to disable this feature of JTextArea component. Could you give me advise. Thanks.

推荐答案

您可以将标记"设置为与插入符号的点"相等.当这些值相等时,没有文本选择:

You can set the "mark" equal to the "dot" of the caret. When these values are equal there is no text selection:

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

public class NoTextSelectionCaret extends DefaultCaret
{
    public NoTextSelectionCaret(JTextComponent textComponent)
    {
        setBlinkRate( textComponent.getCaret().getBlinkRate() );
        textComponent.setHighlighter( null );
    }

    @Override
    public int getMark()
    {
        return getDot();
    }

    private static void createAndShowUI()
    {
        JTextField textField1 = new JTextField("No Text Selection Allowed");
        textField1.setCaret( new NoTextSelectionCaret( textField1 ) );
        textField1.setEditable(false);

        JTextField textField2 = new JTextField("Text Selection Allowed");

        JFrame frame = new JFrame("No Text Selection Caret");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(textField1, BorderLayout.NORTH);
        frame.add(textField2, BorderLayout.SOUTH);
        frame.pack();
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

这篇关于如何在 JTextArea Swing 上禁用文本选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆