Nimbus で行ごとの色分けがどのように機能するかわかりません。クレイジーなようです!!! ここで整理したいと思います。
デモンストレーションのために、赤とピンクの行を交互に表示する JTable が必要だとしましょう(最初の色がどちらであるかは気にしません)。
独自の「モジュロ 2」を実行するカスタム cellRenderer を再定義せず、JTable からのメソッドをオーバーライドせずに、自分のアプリケーションを開始してから、 Nimbus プロパティのみを使用してカスタムの代替行の色を持つ JTable を取得するまでの必須の手順をリストしたいと思います。
これが私が従うことを期待したステップです:
- Nimbus PLAF をインストールする
- 「Table.background」ニンバス プロパティをカスタマイズする
- 「Table.alternateRowColor」ニンバス プロパティをカスタマイズする
- 単純なデータ/ヘッダーで JTable を作成する
- JScrollPane で jTable をラップし、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 プロパティのみを使用して行を交互に色付けする方法は次のとおりです。
public class 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);
}
}