我有一個自定義 AbstractTableModel,我想默認將所有列居中。我知道這是使用 TableCellRenderer 制作的,但我不知道如何在我的代碼中實作它。這是我的課。
import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
public class BiseccionModel extends AbstractTableModel {
private String[] columnNames = {
"i",
"a",
"b",
"xi",
"error",
"f(a)",
"f(xi)"
};
private ArrayList<Biseccion> values;
public BiseccionModel() {
values = new ArrayList<Biseccion>();
}
public BiseccionModel(ArrayList<Biseccion> values) {
this.values = values;
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
@Override
public int getRowCount() {
return values.size();
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Biseccion biseccion = getBiseccion(rowIndex);
switch (columnIndex) {
case 0 -> {
return biseccion.getI();
}
case 1 -> {
return biseccion.getA();
}
case 2 -> {
return biseccion.getB();
}
case 3 -> {
return biseccion.getXi();
}
case 4 -> {
return biseccion.getError();
}
case 5 -> {
return biseccion.getFa();
}
case 6 -> {
return biseccion.getFxi();
}
default -> {
return null;
}
}
}
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
Biseccion biseccion = getBiseccion(rowIndex);
switch (columnIndex) {
case 0 -> biseccion.setI((Integer) value);
case 1 -> biseccion.setA((Double) value);
case 2 -> biseccion.setB((Double) value);
case 3 -> biseccion.setXi((Double) value);
case 4 -> biseccion.setError((Double) value);
case 5 -> biseccion.setFa((Double) value);
case 6 -> biseccion.setFxi((Double) value);
}
fireTableCellUpdated(rowIndex, columnIndex);
}
public Biseccion getBiseccion(int row) {
return values.get(row);
}
}
這是可能的/一個好主意還是我應該堅持在我將 JTables 與自定義模型一起使用的課程中這樣做?
uj5u.com熱心網友回復:
TableModel 不進行渲染。但是,您確實需要通過實作該方法來定義每列的資料型別getColumnClass(...),正如您在上一個問題中所展示的那樣,因此表可以為給定類選擇適當的渲染器。
Double 和 Integer 的默認渲染器將顯示右對齊的數字。
如果您真的希望它們居中,則可以使用該JTable.getDefaultRenderer(...)方法獲取默認渲染器。默認渲染器是 JLabel,因此您可以設定其對齊方式:
DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)table.getDefaultRenderer(Double.class);
renderer.setHorizontalAlignment(JLabel.CENTER);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/456051.html
上一篇:Java中選單快捷方式的多鍵擊鍵
