我正在使用 ListSelectionListenerJTextField
从所选行更新我的 (countryTxt)。
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
public class App {
JFrame frame = new JFrame();
JTable table = new JTable();
DefaultTableModel model = new DefaultTableModel(new Object[][] {},
new String[] { "Country", "City", "Street" });
JButton button = new JButton("Remove");
JTextField countryTxt = new JTextField();
int row;
public App() {
table.setModel(model);
data();
table.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
row = table.getSelectedRow();
countryTxt.setText((String) model
.getValueAt(row, 0));
}
}
});
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
model.removeRow(row);
}
});
frame.add(countryTxt,BorderLayout.NORTH);
frame.add(new JScrollPane(table), BorderLayout.CENTER);
frame.add(button, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
public void data() {
model.addRow(new String[] { "USA", "New York", "First street" });
model.addRow(new String[] { "Russia", "Moscow", "Second street" });
model.addRow(new String[] { "Japan", "Osaka", "Osaka street" });
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new App();
}
});
}
}
但是,当我选择一行并单击 abutton
时,它会出现ArrayIndexOutOfBounds
异常。当我没有在表中选择一行并单击button
一切正常时。valueChanged
显然,我可以在未触发事件时删除一行。所以我的问题是:如何在valueChanged
事件触发后删除一行。提前致谢。