如何在列选择时突出显示JTable的标题?

时间:2014-12-04 23:44:27

标签: java swing jtable

我尝试编写自定义渲染器,但无法激活它的功能:

public class HeaderRenderer extends JPanel implements TableCellRenderer {

        private static final long serialVersionUID = -1247350397731719795L;

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

            int modelColumn = table.convertColumnIndexToModel(column);
            /*
            if( table.getSelectedColumn() == modelColumn ) {
                isSelected = true;
            }
            */

            JComponent ans;

            if (modelColumn == 0) {
                ans = new JLabel("<html><pre>" + getColumnName(column) + "</pre></html>");
            }
            else {
                ans = new JLabel("<html><pre>" + String.valueOf(directory.getCorpus(modelColumn - 1)) + "</pre></html>");

                table.getColumnModel().getColumn(table.convertColumnIndexToView(column)).setPreferredWidth(300);
            }

            //ans.setBorder(BorderFactory.createLineBorder(Color.black));

            ((JLabel) ans).setFont(new Font("SansSerif", Font.PLAIN, 10));
            ans.setForeground(Color.BLUE);
            //((JLabel)ans).setBackground(Color.yellow);
            //ans.setBorder(BorderFactory.createEtchedBorder());
            ans.setBorder(BorderFactory.createLineBorder(Color.black));

            if (isSelected) {
                ans.setBackground(UIManager.getColor("Table.selectionBackground"));
            }
            else {
                ans.setBackground(getBackground());
            }

            ((JLabel) ans).setVerticalAlignment(SwingConstants.TOP);

            JTableHeader header = table.getTableHeader();
            Dimension dim = new Dimension();

            if (ans.getPreferredSize().height > dim.height) {
                dim.height = ans.getPreferredSize().height;
                header.setPreferredSize(dim);
            }

            return ans;

        }

    }

显然,在选择单元格时不会重新绘制标题,因此渲染器不会运行。

如何强制它运行?

0 个答案:

没有答案