我想用defaulttablemodel BOLD制作jtable的标题。 这是我的代码
class TablePanel extends JPanel {
private String[] COLUMNS = {"FAMILY MEMBERS", "STAR (NAKSHATRA)"};
private DefaultTableModel model = new DefaultTableModel(COLUMNS, 0){
public boolean isCellEditable(int row, int column) {
return false;
}
};
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer(){
public void setHorizontalAlignment(int alignment) {
alignment = (int) CENTER_ALIGNMENT;
};
};
public JTable table = new JTable(model){
public void setDefaultRenderer(java.lang.Class<?> columnClass, TableCellRenderer renderer) {
columnClass= String.class;
renderer=centerRenderer;
};
public void setBackground(Color bg) {
bg = Color.yellow;
};
};
我想让列标题为BOLD。任何关于此的提示都表示赞赏
答案 0 :(得分:3)
奇怪的是,表格列标题使用与表格相同的概念来渲染...
DefaultTableCellRenderer header = new DefaultTableCellRenderer();
header.setFont(header.getFont().deriveFont(Font.BOLD));
JTable table = new JTable();
TableColumnModel model = table.getColumnModel();
model.getColumn(0).setHeaderRenderer(header);
例如。但我认为它不会像你想要的那样......
相反,你可以试试像......
DefaultTableModel model = new DefaultTableModel(new Object[]{"<html><b>Happy</b></html>", "Sad"}, 0);
JTable table = new JTable(model);
答案 1 :(得分:3)
渲染器中自定义视觉的清洁(比@ Mad的)策略是围绕默认设置实现包装渲染器:它将所有配置委托为默认配置,然后应用自定义装饰。这样做可以保留LAF特定的视觉效果。
public static class HeaderRenderer implements UIResource, TableCellRenderer {
private TableCellRenderer original;
public HeaderRenderer(TableCellRenderer original) {
this.original = original;
}
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row,
int column) {
Component comp = original.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
comp.setFont(comp.getFont().deriveFont(Font.BOLD));
return comp;
}
}
要使用,请使用包装渲染器替换标头的默认值,并更新LAF的更改:
// replace the inital default with our wrapper
TableCellRenderer original = table.getTableHeader().getDefaultRenderer();
table.getTableHeader().setDefaultRenderer(new HeaderRenderer(original));
// a propertyChangeListener that updates the wrapper
PropertyChangeListener pl = new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
// cleanup (to be on the safe side)
if (table.getTableHeader().getDefaultRenderer() instanceof HeaderRenderer) {
HeaderRenderer renderer = (HeaderRenderer) table.getTableHeader().getDefaultRenderer();
table.getTableHeader().setDefaultRenderer(renderer.original);
}
// invoke to make sure the ui delegate updated the header renderer
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TableCellRenderer r = table.getTableHeader().getDefaultRenderer();
if (!(r instanceof HeaderRenderer)) {
table.getTableHeader().setDefaultRenderer(new HeaderRenderer(r));
table.getTableHeader().repaint();
}
}
});
}
};
// register the listener with the UIManager to get notified on LAF changes
UIManager.addPropertyChangeListener(pl);