Et eksempel fra lageret:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.AbstractTableModel;
public class UpdateTable extends JFrame {
private int n = 0;
private MyModel model = new MyModel();
public UpdateTable() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new BorderLayout());
setTitle("Simple table");
JTable tbl = new JTable(model);
getContentPane().add(new JScrollPane(tbl), BorderLayout.CENTER);
JButton btn = new JButton("Add");
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
n++;
model.add(n, "This is row " + n);
}
});
getContentPane().add(btn, BorderLayout.SOUTH);
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame f = new UpdateTable();
f.setVisible(true);
}
});
}
}
class MyModel extends AbstractTableModel {
private List<String> colnam = new ArrayList<String>();
private List<List<String>> data = new ArrayList<List<String>>();
public MyModel() {
colnam.add("F1");
colnam.add("F2");
}
@Override
public int getColumnCount() {
return colnam.size();
}
@Override
public int getRowCount() {
return data.size();
}
@Override
public String getColumnName(int colix) {
return colnam.get(colix);
}
@Override
public Object getValueAt(int rowix, int colix) {
return data.get(rowix).get(colix);
}
public void add(int f1, String f2) {
List<String> row = new ArrayList<String>();
row.add(Integer.toString(f1));
row.add(f2);
data.add(row);
fireTableDataChanged();
}
}
Her skulle der saa laves en sort metode som sorterer data og saa kalder fireTableDataChanged.