用java,gui实现这样一个代码,建立一个表格,点击表格中的一行,能够展示该行的详细信
时间: 2023-07-14 19:13:08 浏览: 85
以下是一个简单的Java GUI代码示例,用于创建一个表格并在点击表格行时显示详细信息:
```java
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
public class TableDemo extends JFrame implements ActionListener {
private JTable table;
private JTextArea details;
public TableDemo() {
super("Table Demo");
// Create table data
Object[][] data = {
{"John", "Doe", 32},
{"Jane", "Smith", 28},
{"Bob", "Johnson", 45},
{"Lisa", "Williams", 39},
{"Mark", "Brown", 22},
};
// Create table column names
String[] columnNames = {
"First Name", "Last Name", "Age"
};
// Create table model
DefaultTableModel model = new DefaultTableModel(data, columnNames);
// Create table
table = new JTable(model);
// Add table selection listener
table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent event) {
// Get selected row index
int row = table.getSelectedRow();
// If a row is selected
if (row >= 0) {
// Get data for selected row
Object[] rowData = new Object[model.getColumnCount()];
for (int i = 0; i < model.getColumnCount(); i++) {
rowData[i] = model.getValueAt(row, i);
}
// Update details text area with selected row data
details.setText("Selected Row:\n" +
"First Name: " + rowData[0] + "\n" +
"Last Name: " + rowData[1] + "\n" +
"Age: " + rowData[2]);
}
}
});
// Create scroll pane for table
JScrollPane scrollPane = new JScrollPane(table);
// Create details text area
details = new JTextArea(5, 20);
details.setEditable(false);
// Create panel for details text area
JPanel detailsPanel = new JPanel(new BorderLayout());
detailsPanel.setBorder(BorderFactory.createTitledBorder("Details"));
detailsPanel.add(details, BorderLayout.CENTER);
// Create main panel for table and details
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(scrollPane, BorderLayout.CENTER);
mainPanel.add(detailsPanel, BorderLayout.SOUTH);
// Add main panel to frame
getContentPane().add(mainPanel);
// Set window properties
setSize(400, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent event) {
// Handle button click events
}
public static void main(String[] args) {
TableDemo demo = new TableDemo();
demo.setVisible(true);
}
}
```
这个示例创建一个包含名字和年龄的表格,并在底部显示选定行的详细信息。要添加更多列或更改表格数据,只需更改“data”和“columnNames”数组即可。
阅读全文