如何在 Java 中为 JTable 的隔行设置颜色?
JTable 是JComponent 类的子类,可用于创建表格,其中信息显示在多个行和列中。当从 JTable 中选择值时,将生成一个TableModelEvent,通过实现TableModelListener 接口来处理此事件。
我们可以通过重写 JTable 类 prepareRenderer() 方法来为 JTable 的隔行设置颜色 。
语法
public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
示例
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.table.*; public class AlternateRowColorTableTest extends JFrame { public AlternateRowColorTableTest() { setTitle("AlternateRowColorTable Test"); JTable table = new JTable(new Object[][] {{"115", "Ramesh"}, {"120", "Adithya"}, {"125", "Jai"}, {"130", "Chaitanya"}, {"135", "Raja"}}, new String[] {"Employee Id", "Employee Name"}) { public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component comp = super.prepareRenderer(renderer, row, column); Color alternateColor = new Color(200, 201, 210); Color whiteColor = Color.WHITE; if(!comp.getBackground().equals(getSelectionBackground())) { Color c = (row % 2 == 0 ? alternateColor : whiteColor); comp.setBackground(bg); c = null; } return returnComp; } }; add(new JScrollPane(table)); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new AlternateRowColorTableTest(); } }
输出
广告