JTable基本使用
表格创建
public class Ui extends JFrame {
private DefaultTableModel dtm;
private JTable table;
public Ui() {
setTitle("test");
setSize(400, 300);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String[] columnNames = new String[]{"", "歌曲名", "歌手", "专辑", "时长"};
String[][] data = new String[][]{};
dtm = new DefaultTableModel(data, columnNames) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
table = new JTable(dtm);
addRows(20);
JScrollPane jsp = new JScrollPane(table);
add(jsp);
setVisible(true);
}
表数据添加
private void addRows(int count){
String[] arr = new String[5];
for (int i = 0; i < count; i++) {
arr[0] = "" + i;
arr[1] = "七里香" + i;
arr[2] = "Jay Chou" + i;
arr[3] = "七里香" + (i * 2);
arr[4] = "" + (i * 30);
add(arr);
}
}
private void add(String[] arr) {
dtm.addRow(arr);
table.setModel(dtm);
}
运行效果