How to highlight part of a JLabel?

前端 未结 3 1724
没有蜡笔的小新
没有蜡笔的小新 2021-01-11 22:06

Before any one suggests HTML, I explain later why thats not an option here. I have a table that contains a column with text cells in it. I need to be able to highlight some

3条回答
  •  渐次进展
    2021-01-11 22:36

    Thats a great answer, and probably the best solution. But an alternative that some might find simpler is to use a JTextfield instead of a JLabel for rendering then you can use JTextfields highlighting capabilities i.e

    void highlightWhitespaceText(JTextField text)
        {
            text.setHighlighter(AbstractTableCellRenderer.defaultHighlighter);
            try
            {
                Matcher m = AbstractTableCellRenderer.whitespaceStartPattern.matcher(text.getText());
                if (m.matches())
                {
                    text.getHighlighter().addHighlight(m.start(1), m.end(1), AbstractTableCellRenderer.highlightPainter);
                }
                m = AbstractTableCellRenderer.whitespaceEndPattern.matcher(text.getText());
                if (m.matches())
                {
                    text.getHighlighter().addHighlight(m.start(1), m.end(1), AbstractTableCellRenderer.highlightPainter);
                }
            }
            catch (BadLocationException ble)
            {
                //
            }
        }
    

    You can change the properties of a JTextfield so it looks like a jLabel in other respects.

提交回复
热议问题