gpt4 book ai didi

java - 将列添加到现有的 TableModel

转载 作者:搜寻专家 更新时间:2023-11-01 00:59:42 25 4
gpt4 key购买 nike

我有课;

public class A extends AbstractTableModel
{
...
}

我使用 ResultSetMetaData 构建 TableModel 以匹配数据库中的结果集。

public class B extends JPanel
{
...
}

B 类 中,我扩展了 JPanel 并添加了 A 类 来显示我的表格。我希望能够根据表模型的条件添加新列。我试过谷歌搜索,但显示的大多数示例都是基于 DefaultTableModel 而不是 AbstractTableModel

有人知道如何实现吗?

最佳答案

例如

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableColumnHider {

private JTable table;
private TableColumnModel tcm;
private Map hiddenColumns;

public TableColumnHider(JTable table) {
this.table = table;
tcm = table.getColumnModel();
hiddenColumns = new HashMap();
}

public void hide(String columnName) {
int index = tcm.getColumnIndex(columnName);
TableColumn column = tcm.getColumn(index);
hiddenColumns.put(columnName, column);
hiddenColumns.put(":" + columnName, new Integer(index));
tcm.removeColumn(column);
}

public void show(String columnName) {
Object o = hiddenColumns.remove(columnName);
if (o == null) {
return;
}
tcm.addColumn((TableColumn) o);
o = hiddenColumns.remove(":" + columnName);
if (o == null) {
return;
}
int column = ((Integer) o).intValue();
int lastColumn = tcm.getColumnCount() - 1;
if (column < lastColumn) {
tcm.moveColumn(lastColumn, column);
}
}

public static void main(String[] args) {
String[] columnNames = {"Name", "Size", "Type", "Date Modified", "Permissions"};
String[][] data = {
{"bin", "2", "dir", "Jun 9", "drwxr-xr-x"},
{"boot", "3", "dir", "Jun 9", "drwxr-xr-x"},
{"dev", "6", "dir", "Jul 12", "drwxr-xr-x"},
{"etc", "34", "dir", "Jul 12", "drwxr-xr-x"},};
JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
final TableColumnHider hider = new TableColumnHider(table);
JPanel checkBoxes = new JPanel();
for (int i = 0; i < columnNames.length; i++) {
JCheckBox checkBox = new JCheckBox(columnNames[i]);
checkBox.setSelected(true);
checkBox.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent evt) {
JCheckBox cb = (JCheckBox) evt.getSource();
String columnName = cb.getText();

if (cb.isSelected()) {
hider.show(columnName);
} else {
hider.hide(columnName);
}
}
});
checkBoxes.add(checkBox);
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(scrollPane);
frame.getContentPane().add(checkBoxes, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

关于java - 将列添加到现有的 TableModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6793257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com