在Java中,要从另一个类中删除JTable列,可以按照以下步骤进行操作:
import javax.swing.table.AbstractTableModel;
public class CustomTableModel extends AbstractTableModel {
private Object[][] data;
private String[] columnNames;
public CustomTableModel(Object[][] data, String[] columnNames) {
this.data = data;
this.columnNames = columnNames;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public int getRowCount() {
return data.length;
}
@Override
public Object getValueAt(int row, int col) {
return data[row][col];
}
// 自定义的删除列的方法
public void removeColumn(int col) {
// 删除列的逻辑处理
}
}
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JScrollPane;
public class MainClass {
public static void main(String[] args) {
Object[][] data = {{"1", "John", "Doe"}, {"2", "Jane", "Smith"}};
String[] columnNames = {"ID", "First Name", "Last Name"};
CustomTableModel model = new CustomTableModel(data, columnNames);
JTable table = new JTable(model);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table));
frame.pack();
frame.setVisible(true);
}
}
public void removeColumn(int col) {
Object[][] newData = new Object[data.length][data[0].length - 1];
String[] newColumnNames = new String[columnNames.length - 1];
int dataIndex = 0;
int columnIndex = 0;
for (int i = 0; i < data.length; i++) {
for (int j = 0; j < data[i].length; j++) {
if (j != col) {
newData[dataIndex][columnIndex] = data[i][j];
columnIndex++;
}
}
dataIndex++;
columnIndex = 0;
}
int columnNameIndex = 0;
for (int i = 0; i < columnNames.length; i++) {
if (i != col) {
newColumnNames[columnNameIndex] = columnNames[i];
columnNameIndex++;
}
}
data = newData;
columnNames = newColumnNames;
fireTableStructureChanged();
}
这样,当调用removeColumn()方法并传入要删除的列索引时,就可以从JTable中删除指定的列了。
请注意,以上代码仅为示例,实际应用中可能需要根据具体情况进行适当的修改和调整。
领取专属 10元无门槛券
手把手带您无忧上云