简体   繁体   中英

Setting the Color on the row of the JTable using JColorChooser

I am novice to Swing. I just started Swing couple of weeks ago and I stuck at some point..

I have designed a JTable having some rows on clicking (right) it opens a popup menu which have "CHANGE ROW COLOR" option ( JMenuItem ),on clicking which JColorChooser opens up and user can choose the color and same color will be set to the selected row.

Is it possible to do it? How?

enter image description here

enter image description here

If you want the ability to color each row separately then one way is to store the Color as part of the data in the TableModel. So you will need to add the Color as a column in the model.

But you will not want to display this column in the view of the table so you will need to remove it from the view:

table.removeColumn( table.getColumn(...) );

Next you will need to add custom rendering for the table. One way to do this is to add rendering for the entire row. Check out Table Row Rendering for an example of this approach.

So the basic code for the rendering would be something like:

Color background = table.getTableModel.getValueAt(row, ???);

if (background != null)
    c.setBackground( background );

And when you display the color choose you would need to save the Color to the TableModel:

table.getTableModel().setValueAt(color, table.getSelectedRow(), ???);

Another way would be to save the row & the color in a map<Integer, Color>

(use table.getSelectedRow() )

To capture the color from the JColorchooser, use : Color selectedColor = myColorChooser.getSelectionModel().getSelectedColor();

Then, modify the default renderer :

table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {

                final Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                        column);

                if (listOfColor.containKey(row)) {

                    c.setBackground(listOfColor.get(row));

                }

                DefaultTableCellRenderer centerRenderer = (DefaultTableCellRenderer) c;
                centerRenderer.setHorizontalAlignment(SwingConstants.CENTER);
                return c;
            }
        });

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