此代碼主要來自www.java2s.com,其中包含更改如何改變顏色。這不是最漂亮的解決方案,但希望能幫助你。
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
public class MainClass {
public static void main(String args[]) {
String rows[][] = { { "A", "a" }, { "B", "b" }, { "E", "e" } };
String headers[] = { "Upper", "Lower" };
JFrame frame = new JFrame("Label Header");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTable table = new JTable(rows, headers);
JScrollPane scrollPane = new JScrollPane(table);
Border headerBorder = UIManager.getBorder("TableHeader.cellBorder");
JLabel headerLabel1 = new JLabel(headers[0], JLabel.CENTER);
headerLabel1.setBorder(headerBorder);
// Here is where the color is changed.
headerLabel1.setBackground(new Color(255, 0, 0));
headerLabel1.setForeground(new Color(0, 0, 255));
// End of color change.
JLabel headerLabel2 = new JLabel(headers[1], JLabel.CENTER);
headerLabel2.setBorder(headerBorder);
TableCellRenderer renderer = new JComponentTableCellRenderer();
TableColumnModel columnModel = table.getColumnModel();
TableColumn column0 = columnModel.getColumn(0);
TableColumn column1 = columnModel.getColumn(1);
column0.setHeaderRenderer(renderer);
column0.setHeaderValue(headerLabel1);
column1.setHeaderRenderer(renderer);
column1.setHeaderValue(headerLabel2);
frame.add(scrollPane, BorderLayout.CENTER);
frame.setSize(300, 150);
frame.setVisible(true);
}
}
class JComponentTableCellRenderer implements TableCellRenderer {
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
return (JComponent)value;
}
}
最重要的位:
// Here is where the color is changed.
headerLabel1.setBackground(new Color(255, 0, 0));
headerLabel1.setForeground(new Color(0, 0, 255));
// End of color change.
HTH讓我知道你如何與它:)
看起來不錯我會給這個嘗試 – 2009-05-29 10:00:30