java JTABLE - 删除后刷新TextFields数据库中的项目

时间:2014-06-19 09:19:27

标签: java swing user-interface jtable refresh

我在Frame上有文本字段和JTable。当用户单击JTable行或向上和向下移动键时,文本字段填充了这些选定的行值,以便用户可以更新该行。所以问题是当我选择行然后按下删除按钮表刷新但文本字段仍然显示删除的行值。所以此时我不想重置字段。我想在文本字段

中显示已删除行之前的行值

例如,有两行

id  name  
1   hello
2   bello

用户选择了ID 2的行并将其删除。现在文本字段上的值应该是你好,不要低于

1 个答案:

答案 0 :(得分:1)

您可以在ListSelectionListener上使用JTableJTextField根据JTable中的当前选项设置ActionListener元素的文字。按下删除按钮后,您可以让JTableimport java.awt.*; import java.awt.event.*; import javax.swing.border.*; import javax.swing.event.*; import javax.swing.table.*; import javax.swing.*; public class JTableDelete extends JFrame { private static final long serialVersionUID = 1L; private JPanel contentPane; private JTable table; private JTextField textField; public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { JTableDelete frame = new JTableDelete(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public JTableDelete() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); contentPane.setLayout(new BorderLayout(0, 0)); setContentPane(contentPane); table = new JTable(); table.setModel(new DefaultTableModel(new Object[][] { { "Red" }, { "Green" }, { "Blue" }, { "Violet" }, { "Orange" }, }, new String[] { "Colors" })); ListSelectionModel cellSelectionModel = table.getSelectionModel(); cellSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); cellSelectionModel.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { int selectedRow = table.getSelectedRow(); int selectedColumn = table.getSelectedColumn(); if (selectedRow != -1 && selectedColumn != -1) textField.setText((String) table.getValueAt(selectedRow, selectedColumn)); else textField.setText(""); } }); contentPane.add(table, BorderLayout.CENTER); JButton btnDelete = new JButton("Delete"); btnDelete.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); int rowCount = table.getRowCount() - 1; // -1 because counting starts at 0 if (row != -1) { ((DefaultTableModel) table.getModel()).removeRow(row); rowCount--; // 1 less row now if (row < table.getRowCount()) // next selection table.setRowSelectionInterval(row, row); else if (rowCount != -1) // end selection table.setRowSelectionInterval(rowCount, rowCount); } } }); contentPane.add(btnDelete, BorderLayout.SOUTH); textField = new JTextField(); textField.setEnabled(false); contentPane.add(textField, BorderLayout.NORTH); textField.setColumns(10); pack(); } } 中删除所选行,并通过setRowSelectionInterval强制模型中的下一个选择。以下是一个简单的例子:

Row Deletion Animation

{{1}}