Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách đặt màu nền/chữ cho từng cột JTable trong Java

JTable là một lớp con của JComponent để hiển thị cấu trúc dữ liệu phức tạp. JTable tuân theo mẫu Model View Controller (MVC) để hiển thị dữ liệu theo hàng và cột. JTable có thể tạo các giao diện TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener. Chúng ta có thể thay đổi màu nền và màu chữ cho từng cột của JTable bằng cách tùy chỉnh lớp DefaultTableCellRenderer chỉ có một phương thức getTableCellRendererComponent() để triển khai.

Ví dụ

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();
    }
}

// Tùy chỉnh code để đặt màu nền và chữ cho từng cột 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;
    }
}

Kết quả

Cách đặt màu nền/chữ cho từng cột JTable trong Java