import java.awt.event.*; import java.awt.*; import javax.swing.*; import javax.swing.table.DefaultTableModel; public class MyTableWin extends JFrame implements ActionListener { Object rows[][] = { { "001", "zhang", "03/04/2002", "Computer" }, { "002", "Li", "05/10/2002", "Chinese" }, { "003", "Wang", "09/10/2002", "English" } }; String cols[] = { "number", "name", "birthday", "department" }; JTable table; JLabel lbl_show; JTextField txt_show; JButton btn_update; JPanel pSouth, pNorth; JScrollPane jp; public MyTableWin() { table = new JTable(rows, cols); // 表格里点谁就显示谁 table.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { int row = table.getSelectedRow(); int column = table.getSelectedColumn(); Object selectedvalue = table.getModel().getValueAt(row, column); txt_show.setText((String) selectedvalue); btn_update.setEnabled(true); } }); lbl_show = new JLabel("Info."); txt_show = new JTextField(15); btn_update = new JButton("Update"); btn_update.setEnabled(false); btn_update.addActionListener(this); pSouth = new JPanel(); pNorth = new JPanel(); jp = new JScrollPane(table); pNorth.add(jp); pSouth.add(lbl_show); pSouth.add(txt_show); pSouth.add(btn_update); add(pNorth, BorderLayout.CENTER); add(pSouth, BorderLayout.SOUTH); setVisible(true); setSize(800, 500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); int column = table.getSelectedColumn(); rows[row][column] = txt_show.getText(); int option = JOptionPane.showConfirmDialog(this, "do you confirm to update the table content?", "warning", JOptionPane.OK_CANCEL_OPTION); if (option == JOptionPane.OK_OPTION) { table.setModel(new DefaultTableModel(rows, cols)); } btn_update.setEnabled(false); } public static void main(String[] args) { MyTableWin win = new MyTableWin(); } }修改该程序,使得点击表格时,在控件台显示所在行一行的数据。
时间: 2024-01-13 11:03:03 浏览: 61
import java.awt.docx
可以在鼠标点击事件中获取所在行的数据,然后显示在控件台上。修改代码如下:
```
table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
int row = table.getSelectedRow();
Object[] rowData = new Object[cols.length];
for (int i = 0; i < cols.length; i++) {
rowData[i] = table.getModel().getValueAt(row, i);
}
String rowInfo = "Row " + (row + 1) + ": " + Arrays.toString(rowData);
txt_show.setText(rowInfo);
btn_update.setEnabled(true);
}
});
```
这样修改后,点击表格时就可以在控件台中显示所在行一行的数据了。
阅读全文