|
| 1 | +import java.awt.*; |
| 2 | +import java.awt.event.*; |
| 3 | +import java.util.*; |
| 4 | +import javax.swing.*; |
| 5 | +import javax.swing.table.*; |
| 6 | + |
| 7 | +public class ButtonColumnDemo |
| 8 | +{ |
| 9 | + public static void main(String[] args) |
| 10 | + { |
| 11 | + SwingUtilities.invokeLater(new Runnable() { |
| 12 | + public void run() { |
| 13 | + createAndShowGUI(); |
| 14 | + } |
| 15 | + }); |
| 16 | + } |
| 17 | + |
| 18 | + public static void createAndShowGUI() |
| 19 | + { |
| 20 | + UIManager.put("Button.defaultButtonFollowsFocus", Boolean.TRUE); |
| 21 | + |
| 22 | + String[] columnNames = {"First Name", "Last Name", ""}; |
| 23 | + Object[][] data = |
| 24 | + { |
| 25 | + {"Homer", "Simpson", "delete Homer"}, |
| 26 | + {"Madge", "Simpson", "delete Madge"}, |
| 27 | + {"Bart", "Simpson", "delete Bart"}, |
| 28 | + {"Lisa", "Simpson", "delete Lisa"}, |
| 29 | + }; |
| 30 | + |
| 31 | + DefaultTableModel model = new DefaultTableModel(data, columnNames); |
| 32 | + JTable table = new JTable( model ); |
| 33 | + JScrollPane scrollPane = new JScrollPane( table ); |
| 34 | + |
| 35 | + Action delete = new AbstractAction() |
| 36 | + { |
| 37 | + public void actionPerformed(ActionEvent e) |
| 38 | + { |
| 39 | + |
| 40 | + JTable table = (JTable)e.getSource(); |
| 41 | + int modelRow = Integer.valueOf( e.getActionCommand() ); |
| 42 | + Object delete = table.getModel().getValueAt(modelRow, 2); |
| 43 | + Window window = SwingUtilities.windowForComponent(table); |
| 44 | + |
| 45 | + int result = JOptionPane.showConfirmDialog( |
| 46 | + window, |
| 47 | + "Are you sure you want to " + delete, |
| 48 | + "Delete Row Confirmation", |
| 49 | + JOptionPane.YES_NO_OPTION); |
| 50 | + |
| 51 | + if (result == JOptionPane.YES_OPTION) |
| 52 | + { |
| 53 | +// System.out.println( "Deleting row: " + modelRow); |
| 54 | + ((DefaultTableModel)table.getModel()).removeRow(modelRow); |
| 55 | + } |
| 56 | + } |
| 57 | + }; |
| 58 | + |
| 59 | + ButtonColumn buttonColumn = new ButtonColumn(table, delete, 2); |
| 60 | + buttonColumn.setMnemonic(KeyEvent.VK_D); |
| 61 | + |
| 62 | + JFrame frame = new JFrame("Table Button Column"); |
| 63 | + frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); |
| 64 | + frame.add( scrollPane ); |
| 65 | + frame.setSize(400, 160); |
| 66 | + frame.setLocationRelativeTo(null); |
| 67 | + frame.setVisible(true); |
| 68 | + } |
| 69 | +} |
0 commit comments