日期:2014-05-20 浏览次数:20847 次
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
public class DemoTable extends JFrame {
private JButton btn;
private JTable tbl;
private Model m;
public DemoTable (){
initComponents();
}
private void initComponents(){
m = new Model();
tbl = new JTable(m);
JPanel pan = new JPanel();
this.setContentPane(pan);
pan.setLayout(new BorderLayout());
JScrollPane jsp = new JScrollPane();
jsp.setViewportView(tbl);
pan.add(jsp, BorderLayout.CENTER);
}
private static void createAndShowGui() {
DemoTable dt = new DemoTable();
dt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
dt.setMinimumSize(new Dimension(500, 400));
dt.setLocationRelativeTo(null);
dt.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGui();
}
});
}
static class Model extends DefaultTableModel {
private ArrayList<String> data = new ArrayList();
public Model(){
data = new ArrayList();
}
public boolean isCellEditable(){
return false;
}
public void addRow(String rowData) {
data.add(rowData);
}
public void removeRow(String rowData) {
data.remove(rowData);
}
@Override
public int getRowCount() {
return data.size();
}
@Override
public int getColumnCount() {
return 1;
}
public Object getVaultAt(int row, int col) {
return data.get(row);
}
}
}
@Override
public int getRowCount() {
return getData().size();
}
private List<String> getData() {
if( data == null )
data = new ArrayList<String>();
return data;
}