我不明白在 Nimbus 中交替行着色是如何工作的。看起来简直是疯了!!!我想在这里澄清一下。
对于演示,假设我们想要一个交替红色和粉红色行的 JTable(我不在乎第一个颜色是哪种颜色)。
在不重新定义执行自己的“模 2”事情的自定义 cellRenderer的情况下,并且不覆盖 JTable 中的任何方法,我想列出启动应用程序和仅使用 Nimbus 属性获取具有自定义备用行颜色的 JTable 之间的强制性步骤。
以下是我希望遵循的步骤:
- 安装 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);
}
}