请帮我实现jtable中的crud
时间: 2024-03-22 12:39:42 浏览: 26
好的,可以使用以下步骤来实现 jtable 中的 CRUD 操作:
1. 创建 JTable 对象并设置数据模型,如下:
```
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
```
2. 向数据模型中添加列名和数据,如下:
```
model.addColumn("ID");
model.addColumn("名称");
model.addColumn("价格");
Object[] row1 = {1, "商品1", 10.0};
Object[] row2 = {2, "商品2", 20.0};
model.addRow(row1);
model.addRow(row2);
```
3. 添加 CRUD 操作的按钮和事件监听器,如下:
```
JButton addButton = new JButton("添加");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] row = {idField.getText(), nameField.getText(), priceField.getText()};
model.addRow(row);
idField.setText("");
nameField.setText("");
priceField.setText("");
}
});
JButton updateButton = new JButton("更新");
updateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row != -1) {
model.setValueAt(idField.getText(), row, 0);
model.setValueAt(nameField.getText(), row, 1);
model.setValueAt(priceField.getText(), row, 2);
idField.setText("");
nameField.setText("");
priceField.setText("");
}
}
});
JButton deleteButton = new JButton("删除");
deleteButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int row = table.getSelectedRow();
if (row != -1) {
model.removeRow(row);
idField.setText("");
nameField.setText("");
priceField.setText("");
}
}
});
```
4. 将按钮和输入框添加到面板上,如下:
```
JPanel panel = new JPanel(new FlowLayout());
panel.add(new JLabel("ID:"));
panel.add(idField);
panel.add(new JLabel("名称:"));
panel.add(nameField);
panel.add(new JLabel("价格:"));
panel.add(priceField);
panel.add(addButton);
panel.add(updateButton);
panel.add(deleteButton);
```
5. 将表格和面板添加到 JFrame 上并显示,如下:
```
JFrame frame = new JFrame("商品管理");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(table), BorderLayout.CENTER);
frame.add(panel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
```
以上就是简单的实现 jtable 中的 CRUD 操作的步骤。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)