我使用ListSelectionListener從選定行更新我的JTextField
(countryTxt)。觸發valueChanged事件後從JTable刪除行
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();
}
});
}
}
但是,當我選擇一行並單擊button
它trows我和ArrayIndexOutOfBounds
例外。當我不在我的表格中選擇一行並單擊button
時,一切正常。當valueChanged
事件沒有被觸發時,顯然我可以刪除一行。所以我的問題是:如何在valueChanged
事件觸發後刪除一行。提前致謝。
1)爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 2)*「請幫忙?」*請提出一個(具體的)問題。 – 2012-07-25 00:04:28
嗯......問題是:爲什麼刪除後我的數據不能添加到表中? – 2012-07-25 00:12:04
好問題。爲什麼不把它編輯成..問題。 SSCCE呢? – 2012-07-25 00:18:39