【发布时间】:2012-10-12 01:47:17
【问题描述】:
我不明白 Nimbus 中交替行着色的工作原理。看起来简直是疯了!!!我想在这里澄清一下。
为了演示,假设我们想要一个交替红色和粉红色行的 JTable(我不在乎第一个是哪种颜色)。
不重新定义自定义 cellRenderers 来执行他们自己的“模 2”事情,并且不覆盖 JTable 中的任何方法,我想列出启动应用程序和使用自定义替代获取 JTable 之间的强制性步骤行颜色仅使用 Nimbus 属性。
以下是我希望遵循的步骤:
- 安装 Nimbus PLAF
- 自定义“Table.background”nimbus 属性
- 自定义“Table.alternateRowColor”nimbus 属性
- 使用简单的数据/标题创建 JTable
- 将 jTable 包装在 JScrollPane 中并将其添加到 JFrame
- 显示 JFrame
这里是源代码:
public class JTableAlternateRowColors implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JTableAlternateRowColors());
}
@Override
public void run() {
try {
UIManager.setLookAndFeel(new NimbusLookAndFeel());
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
UIManager.getDefaults().put("Table.background", Color.RED);
UIManager.getDefaults().put("Table.alternateRowColor", Color.PINK);
final JFrame jFrame = new JFrame("Nimbus alternate row coloring");
jFrame.getContentPane().add(new JScrollPane(new JTable(new String[][] {
{"one","two","three"},
{"one","two","three"},
{"one","two","three"}
}, new String[]{"col1", "col2", "col3"}
)));
jFrame.setSize(400, 300);
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jFrame.setVisible(true);
}
}
这是 JDK6 代码。 有人能告诉我这里出了什么问题吗?
根据@kleopatra 的评论和整个社区的贡献,这里是一种/仅使用 Nimbus 属性获得备用行着色的方法
公共类 JTableAlternateRowColors 实现 Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JTableAlternateRowColors());
}
@Override
public void run() {
try {
UIManager.setLookAndFeel(new NimbusLookAndFeel());
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
UIManager.put("Table.background", new ColorUIResource(Color.RED));
UIManager.put("Table.alternateRowColor", Color.PINK);
UIManager.getLookAndFeelDefaults().put("Table:\"Table.cellRenderer\".background", new ColorUIResource(Color.RED));
final JFrame jFrame = new JFrame("Nimbus alternate row coloring");
final JTable jTable = new JTable(new String[][]{
{"one", "two", "three"},
{"one", "two", "three"},
{"one", "two", "three"}
}, new String[]{"col1", "col2", "col3"});
jTable.setFillsViewportHeight(true);
jFrame.getContentPane().add(new JScrollPane(jTable));
jFrame.setSize(400, 300);
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jFrame.setVisible(true);
}
}
【问题讨论】:
-
没有任何问题。代码对我来说很好,除了 jdk6 的第一行和第三行是粉红色的,而 jdk7 只有第二行是。
-
不,没有什么疯狂的,必须接受,所有 Randerer 都可以不受限制地工作(对于在 API 中实现 Renderer 的工作),因为 UIManager 必须覆盖 Nimbus Default 中的 proeprs Key(s),当然有时颜色,Painter 某处,问题可能仅与 XxxUIResouces 相关(基本上与问题 1-8 无关),每个键都已正确描述...,顺便说一句,问题中的形式,尤其是第 1-8 点是 vWorker 的重要补充.com
-
@DenisTulskiy 没有在红色和粉红色之间交替的行实际上是错误的。要么是我,要么是 Nimbus,但我们中的一个人错了!
-
在这种情况下,我通常不得不深入研究 Nimbus 源代码,看看它是如何绘制东西的。我建议你也参加那段很棒的旅程:)
-
没有在红色和粉色之间交替的行实际上是错误的在你的问题中添加这句话,水晶球在星期一早上是出了名的不可靠;-)
标签: java swing jtable render nimbus