【问题标题】:Change text selection type in a JTextArea更改 JTextArea 中的文本选择类型
【发布时间】:2014-07-22 01:50:14
【问题描述】:

In most of the text editors, I have seen that when text is selected, all the line changes the color to the selection color.

但是在 JTextArea 中,在选择过程中只有文本颜色在选择过程中发生变化。

如何在 JTextArea 中实现上述选择类型,其中所有选择区域都是彩色的?我找不到任何可以完成这项工作的方法。

【问题讨论】:

    标签: java swing user-interface textarea swing-highlighter


    【解决方案1】:

    也许DefaultHighlighter#setDrawsLayeredHighlights(false) 会起作用:

    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.text.*;
    
    public class SelectionTypeTest {
      public JComponent makeUI() {
        JTextArea textArea = new JTextArea();
        DefaultHighlighter hl = (DefaultHighlighter) textArea.getHighlighter();
        System.out.println(hl.getDrawsLayeredHighlights());
        hl.setDrawsLayeredHighlights(false);
        textArea.setSelectionColor(Color.RED);
        textArea.setSelectedTextColor(Color.WHITE);
        try (Reader reader = new BufferedReader(new InputStreamReader(
              new FileInputStream("SelectionTypeTest.java"), "UTF-8"))) {
          textArea.read(reader, "");
        } catch (Exception ex) {
          ex.printStackTrace();
        }
        return new JScrollPane(textArea);
      }
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          @Override public void run() {
            createAndShowGUI();
          }
        });
      }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new SelectionTypeTest().makeUI());
        f.setSize(320, 240);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
      }
    }
    

    【讨论】:

    • 感谢 setDrawsLayeredHighlights,因为我用选中/未选中覆盖了荧光笔
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-06
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 2013-04-11
    相关资源
    最近更新 更多