失去焦点后,jTextArea停止在文本上突出显示

时间:2013-08-16 12:23:54

标签: java swing jtextcomponent swing-highlighter

当我的jTextArea处于焦点时,它允许文本突出显示,但它在失去焦点时不显示文本选择。即使用户将焦点移动到相关jFrame上的另一个组件,是否可以继续显示文本突出显示?

2 个答案:

答案 0 :(得分:7)

插入符选择的一个简单解决方法是DefaultCaret的简单子类:

textArea.setCaret(new DefaultCaret() {
   @Override
   public void setSelectionVisible(boolean visible) {
      super.setSelectionVisible(true);
   }
});

答案 1 :(得分:3)

  

但在失去焦点时不显示文字选择。

有三种方式:

enter image description here

  • 或以编程方式覆盖荧光笔

enter image description here

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;

public class MultiHighlight implements ActionListener {

    private JTextComponent comp;
    private String charsToHighlight;

    public MultiHighlight(JTextComponent c, String chars) {
        comp = c;
        charsToHighlight = chars;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Highlighter h = comp.getHighlighter();
        h.removeAllHighlights();
        String text = comp.getText().toUpperCase();
        for (int j = 0; j < text.length(); j += 1) {
            char ch = text.charAt(j);
            if (charsToHighlight.indexOf(ch) >= 0) {
                try {
                    h.addHighlight(j, j + 1, DefaultHighlighter.DefaultPainter);
                } catch (BadLocationException ble) {
                }
            }
        }
    }

    public static void main(String args[]) {
        final JFrame frame = new JFrame("MultiHighlight");
        frame.add(new JTextField("Another focusable JComponents"), BorderLayout.NORTH);
        JTextArea area = new JTextArea(10, 20);
        area.setText("This is the story\nof the hare who\nlost his spectacles."
                + "\nThis is the story\nof the hare who\nlost his spectacles.");
        frame.getContentPane().add(new JScrollPane(area), BorderLayout.CENTER);
        JButton b = new JButton("Highlight All Vowels");
        b.addActionListener(new MultiHighlight(area, "aeiouAEIOU"));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(b, BorderLayout.SOUTH);
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
}