How to change cell's border whenever new cell

2019-09-02 03:10发布

问题:

I want to change border of cell whenever it is selected regardless by mouse or by keyboard. It is hard to find smth on net. I tried to use ListSelectionListener but this doesn't work.

If you know some good way to change cell's border, please, reply. I welcome any ideas.

Thank you!

回答1:

Use a customized TableCellRenderer to do something different when the cell is selected.

http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#renderer

Looking at the code from the above example you can see how you would need to look at the isSelected boolean parameter.

 public Component getTableCellRendererComponent(
                        JTable table, Object color,
                        boolean isSelected, boolean hasFocus,
                        int row, int column) {
    Color newColor = (Color)color;
    setBackground(newColor);
    if (isBordered) {
        if (isSelected) {
            ...
            //selectedBorder is a solid border in the color
            //table.getSelectionBackground().
            setBorder(selectedBorder);
        } else {
            ...
            //unselectedBorder is a solid border in the color
            //table.getBackground().
            setBorder(unselectedBorder);
        }
    }

However, in your implementation just extend DefaultTableCellRenderer and call super() version of getTableCellRendererComponent first and just change the cell color.



回答2:

This is the default behaviour. The cell border is set based on the Table.focusCellHighlightBorder property of the table. So you can change the default Border by using the UIManager. See UIManager Defaults for more information.

If for some reason this doesn't meet your requirements then I would check out Table Row Renderering which will allow you do this in one place instead of creating a custom renderer for every data type in your table.