JTable JComponent 의 하위 클래스입니다. 복잡한 데이터 구조를 표시하기 위한 클래스입니다. JTable 구성 요소는 MVC(Model View Controller) 디자인 패턴을 따를 수 있습니다. 행과 열에 데이터를 표시합니다. 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;
}
} 출력
