使用JColorChooser在JTable的行上设置颜色 [英] Setting the Color on the row of the JTable using JColorChooser

查看:69
本文介绍了使用JColorChooser在JTable的行上设置颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我设计了一个JTable,它在单击时(右)有一些行,它会打开一个弹出菜单,该菜单具有更改行颜色"选项(JMenuItem),单击此菜单会打开JColorChooser,用户可以选择颜色和相同颜色将设置为所选行.

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?

在此处输入图片描述

在此处输入图片描述

推荐答案

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

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

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

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

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

这篇关于使用JColorChooser在JTable的行上设置颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆