例如
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Stack;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableColumn;
public class MyDialog extends JDialog {
private static final long serialVersionUID = 1L;
private String[] columnNames = {"First Name", "Last Name", "Sport", "# of Years", "Vegetarian"};
private Stack<TableColumn> colDeleted = new Stack<TableColumn>();
public MyDialog() {
Object[][] data = {{"Mary", "Campione", "Snowboarding", new Integer(5), false},
{"Alison", "Huml", "Rowing", new Integer(3), true},
{"Kathy", "Walrath", "Knitting", new Integer(2), false},
{"Sharon", "Zakhour", "Speed reading", new Integer(20), true},
{"Philip", "Milne", "Pool", new Integer(10), false}};
final JTable table = new javax.swing.JTable(data, columnNames);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
add(new JScrollPane(table));
final JButton button1 = new JButton("Add Col");
final JButton button = new JButton("Remove Last Col");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (table.getColumnCount() > 0) {
TableColumn colToDelete = table.getColumnModel().getColumn(table.getColumnCount() - 1);
table.removeColumn(colToDelete);
table.validate();
colDeleted.push(colToDelete);
button1.setEnabled(true);
} else {
button.setEnabled(false);
}
}
});
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (colDeleted.size() > 0) {
table.addColumn(colDeleted.pop());
table.validate();
button.setEnabled(true);
} else {
button1.setEnabled(false);
}
}
});
JPanel southPanel = new JPanel();
southPanel.add(button);
southPanel.add(button1);
add(southPanel, BorderLayout.SOUTH);
setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
pack();
setLocation(150, 150);
setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
MyDialog myDialog = new MyDialog();
}
});
}
}