如何在 Java 中为 JTable 的各列设置背景/前景颜色?


JTableJComponent 类的子类,用于展示复杂数据结构。JTable 组件可以遵循 模型视图控制器(MVC)设计模式,将数据呈现在行和列中。JTable 可以生成 TableModelListener、TableColumnModelListener、ListSelectionListener、CellEditorListener、RowSorterListener 接口。我们可以通过自定义 DefaultTableCellRenderer 类来更改 JTable 各列的背景色和前景色,并且这个类只有一个方法 getTableCellRendererComponent() 来执行它。

示例

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
public class JTableColumnColorTest extends JFrame {
   private JTable table;
   private TableColumn tColumn;
   public JTableColumnColorTest() {
      setTitle("JTableColumnColor Test");
      table = new JTable(10, 5);
      tColumn = table.getColumnModel().getColumn(2);
      tColumn.setCellRenderer(new ColumnColorRenderer(Color.lightGray, Color.red));
      add(new JScrollPane(table), BorderLayout.CENTER);
      setSize(400, 300);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String [] args) {
      new JTableColumnColorTest();
   }
}
// Customize the code to set the background and foreground color for each column of a JTable
class ColumnColorRenderer extends DefaultTableCellRenderer {
   Color backgroundColor, foregroundColor;
   public ColumnColorRenderer(Color backgroundColor, Color foregroundColor) {
      super();
      this.backgroundColor = backgroundColor;
      this.foregroundColor = foregroundColor;
   }
   public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,   boolean hasFocus, int row, int column) {
      Component cell = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
      cell.setBackground(backgroundColor);
      cell.setForeground(foregroundColor);
      return cell;
   }
}

输出

更新于:2020-02-10

3K+ 浏览量

开足马力 职业生涯

通过完成课程获得认证

立即开始
广告
© . All rights reserved.