简体   繁体   中英

How to set the background color of target cells in a jtable?

I don't want to set the background color for all the cells in the jtable, just the ones I choose. How do i go about doing this?

您需要使用自定义渲染器

You might find the concept presented in Table Row Renderering easier to implement. Maybe keep a Set of Points (representing a cell you want to color). Or maybe even a Map of Points and Colors.

    final JTable table = new JTable(tableModel);
    table.getTableHeader().addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent mouseEvent) {
            int selectedHeader = table.convertColumnIndexToModel(table
                    .columnAtPoint(mouseEvent.getPoint()));

            table.getColumn(table.getColumnName(selectedHeader))
                    .setCellRenderer(new DefaultTableCellRenderer() {
                        public void setBackground(Color c) {
                            super.setBackground(Color.blue);
                        }
                    });
        };
    });

You'll need to create a custom CellRenderer and call it in your custom JTable's getCellRenderer(int col, int rol) method.

See http://self-reference.com/tech/swing.html for a good example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM