एक JTable, JComponent क्लास का एक सबक्लास है जो जटिल डेटा स्ट्रक्चर्स को प्रदर्शित करने के लिए है। एक 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;
}
}
आउटपुट
