0

我正在制作一个程序,我需要能够JTextArea通过我的代码编辑 a 的突出显示功能,但我不希望用户能够通过鼠标突出显示。那,或者我需要某种能够JTextArea手动绘制的方法(看起来像突出显示)。

我真的没有任何代码明智的做法,因为我不知道如何实现它。

编辑:我知道如何在文本上绘画,但我需要绘画像突出显示一样透明。

4

3 回答 3

3

你可以从这段代码开始。String findstr它在整个文本区域中找到用户给出的单词并突出显示该单词。您可以使用它在文本区域中多次查找和突出显示某个单词,直到它到达文本区域内容的末尾。

String findstr = findTextField.getText().toUpperCase(); // User Input Word to find
int findstrLength = findstr.length();                   
String findtextarea = textarea.getText().toUpperCase(); // TextArea Content
Highlighter h = textarea.getHighlighter();
h.removeAllHighlights();
try
    {
        int index=0;
         while(index>=0) {
        index = findtextarea.indexOf(findstr,index);
        if (index > 0) {
           h.addHighlight(index,index+findstrLength, DefaultHighlighter.DefaultPainter);
        }
        index++; // try adding this to allow you to look for the next index.
    }
    }
于 2013-03-18T22:27:18.860 回答
3

我不希望用户能够通过鼠标突出显示

这就是所谓的“选择”。您可以使用自定义插入符号在文本组件上禁用此功能:

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();
            }
        });
    }
}
于 2013-03-18T23:35:32.637 回答
1

See the Highlighter.HighlightPainter interface, that easily (questionable), allows you to change the appearance of the highlight.

There are some concrete implementations, but you can define your own.

于 2013-03-18T22:06:36.810 回答