How to change cell's border whenever new cell is selected in jtable?

南笙酒味 提交于 2019-12-13 04:42:51

问题


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.



来源:https://stackoverflow.com/questions/19863490/how-to-change-cells-border-whenever-new-cell-is-selected-in-jtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!