java,gui,如何删掉表格中的某一行数据
时间: 2023-07-15 18:12:32 浏览: 132
如果你使用的是Java Swing的JTable组件展示表格数据,可以通过以下步骤来删除表格中的某一行数据:
1. 获取选中的行号
```java
int selectedRow = table.getSelectedRow();
```
2. 删除选中的行数据
```java
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.removeRow(selectedRow);
```
3. 刷新表格
```java
model.fireTableDataChanged();
```
完整代码示例:
```java
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TableDemo extends JFrame {
private JTable table;
private JButton deleteButton;
public TableDemo() {
setTitle("Table Demo");
setSize(400, 300);
String[] columnNames = {"Name", "Age", "Gender"};
Object[][] data = {
{"Alice", 20, "Female"},
{"Bob", 25, "Male"},
{"Charlie", 30, "Male"},
{"David", 35, "Male"},
};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
deleteButton = new JButton("Delete");
deleteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int selectedRow = table.getSelectedRow();
if (selectedRow != -1) {
model.removeRow(selectedRow);
model.fireTableDataChanged();
}
}
});
JPanel buttonPanel = new JPanel();
buttonPanel.add(deleteButton);
Container contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(table.getTableHeader(), BorderLayout.NORTH);
contentPane.add(table, BorderLayout.CENTER);
contentPane.add(buttonPanel, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new TableDemo();
}
}
```
在这个例子中,我们创建了一个JTable组件来展示一个简单的表格。当用户点击“Delete”按钮时,会删除选中的行数据并刷新表格。
阅读全文