本文介绍了JTable添加/删除行到自定义表模型(更新表显示)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有人有一个很好的例子,说明如何使用自定义表模型从JTable添加/删除行?我似乎遇到的问题是当我添加或删除项目时如何让表不断更新。
Does anyone have a good example of how to Add/Remove rows from a JTable using a custom table model? The issue I seem to be having is how to have the table keep updating when I add or remove items.
这里真正简单的想法就是在我的桌子上面添加一个添加和删除按钮,允许用户动态更改表格。
The real simple idea here is to have an add and remove button above my table which allows the user on the fly to change the table.
推荐答案
以下是添加行的示例:
import java.awt.BorderLayout;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JViewport;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
public class RowAdder extends JFrame {
final SimpleModel tableData = new SimpleModel();
JTable table = new JTable(tableData);
public static void main(String[] args) {
RowAdder ra = new RowAdder();
ra.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ra.setSize(400, 300);
ra.setVisible(true);
}
public RowAdder() {
final JTextField textField = new JTextField();
setLayout(new BorderLayout());
add(new JScrollPane(table), BorderLayout.CENTER);
textField.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
tableData.addText(textField.getText());
textField.setText("");
}
});
add(textField, BorderLayout.SOUTH);
}
}
class SimpleModel extends AbstractTableModel {
Vector textData = new Vector();
public void addText(String text) {
textData.addElement(text);
fireTableDataChanged();
}
public int getRowCount() {
return textData.size();
}
public int getColumnCount() {
return 3;
}
public Object getValueAt(int row, int column) {
return textData.elementAt(row);
}
}
以上参考来自:
查看本教程关于JTable:
Checkout this tutorial about JTable:
特别适用于餐桌模型检查:
Specifically for table model check:
我认为本教程应该回答你的所有问题。
I think this tutorial should answer all your question.
这篇关于JTable添加/删除行到自定义表模型(更新表显示)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!