Swing超基础学习总结——6、JTable和JScrollPane

时间:2023-01-27 00:16:54

Swing超基础学习总结最后一篇


JTable初始化:

Swing超基础学习总结——6、JTable和JScrollPane
注:初始化方法很多,在这里只演示两种方法;使用TableModel时建立用DefaultTableModel


初始化方法1:

JFrame frame = new JFrame();
String[] columnNames = { "火影", "风影", "雷影", "水影", "土影" };
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
JTable jTable = new JTable(model);
//JScorollPane是滚动条,即把参数中的组件对象加上滚动条
JScrollPane scrollPane = new JScrollPane(jTable);

......

初始化方法2:

JFrame f = new JFrame();
Object[][] playerInfo = { { "初代火影", "初代风影", "初代雷影", "初代水影", "初代土影" },
{ "初代火影", "初代风影", "初代雷影", "初代水影", "初代土影" } };
String[] Names = { "火影", "风影", "雷影", "水影", "土影" };
JTable table = new JTable(playerInfo, Names);
//同上
JScrollPane scrollPane = new JScrollPane(table);

添加/删除数据

步骤1:①先获取model

DefaultTableModel model2 = (DefaultTableModel) jTable.getModel();

步骤2:②执行相应操作

//添加一行数据
String[] column1 = { "初代火影", "初代风影", "初代雷影", "初代水影", "初代土影" };
model.addRow(column1);
//删除某一行
model.removeRow(0);

完整代码(初始化方法1)

JFrame frame = new JFrame();
frame.setTitle("JTable测试");
String[] columnNames = { "火影", "风影", "雷影", "水影", "土影" };
DefaultTableModel model = new DefaultTableModel(columnNames, 0);

JTable jTable = new JTable(model);

JScrollPane scrollPane = new JScrollPane(jTable);
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);

// 获取JTable中的model
DefaultTableModel model2 = (DefaultTableModel) jTable.getModel();
String[] column1 = { "初代火影", "初代风影", "初代雷影", "初代水影", "初代土影" };
model.addRow(column1);

//获取第一行
//model.removeRow(0);