繁体   English   中英

使用JColorChooser在JTable的行上设置颜色

[英]Setting the Color on the row of the JTable using JColorChooser

我是Swing的新手。 我几周前才刚开始使用Swing,但在某个时候我还是停留了。

我设计了一个JTable ,单击时有一些行(右),它会打开一个弹出菜单,其中包含“ CHANGE ROW COLOR”选项( JMenuItem ),单击此JColorChooser打开,用户可以选择颜色,并且相同的颜色将设置为选定的行。

有可能做到吗? 怎么样?

在此处输入图片说明

在此处输入图片说明

如果您希望能够为每行分别着色,那么一种方法是将Color作为数据的一部分存储在TableModel中。 因此,您将需要在模型中将颜色添加为列。

但是您不想在表视图中显示此列,因此需要从视图中将其删除:

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

接下来,您将需要为表格添加自定义呈现。 一种方法是为整个行添加渲染。 查看表行渲染以获取此方法的示例。

因此,渲染的基本代码如下所示:

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

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

当显示颜色时,您需要将颜色保存到TableModel中:

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

另一种方法是将行和颜色保存在map<Integer, Color>

(use table.getSelectedRow() )

要从JColorchooser捕获颜色,请使用: Color selectedColor = myColorChooser.getSelectionModel().getSelectedColor();

然后,修改默认渲染器:

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;
            }
        });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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