JAVA用户图形界面往表格里添加内容的代码。
时间: 2024-05-10 09:19:32 浏览: 13
以下是一个添加内容到表格的 Java 代码示例:
```java
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class AddToTableExample extends JFrame {
private JTable table;
private DefaultTableModel model;
public AddToTableExample() {
// 创建表格模型
model = new DefaultTableModel();
model.addColumn("ID");
model.addColumn("Name");
model.addColumn("Age");
// 创建表格并设置模型
table = new JTable(model);
// 创建滚动面板并添加表格
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
// 创建按钮
JButton addButton = new JButton("Add Row");
addButton.addActionListener(e -> {
// 添加新行
model.addRow(new Object[]{1, "John", 30});
});
getContentPane().add(addButton, BorderLayout.SOUTH);
// 设置窗口属性
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
}
public static void main(String[] args) {
new AddToTableExample();
}
}
```
在这个例子中,我们创建了一个 `JTable` 和一个 `DefaultTableModel`,并将它们关联起来。然后我们创建一个包含一个 “Add Row” 按钮的窗口,当用户点击按钮时,我们通过 `model.addRow()` 方法向表格添加新行。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)