简单实现JTable增删改-2-含JTextField
简单实现JTable增删改-2-含JTextField
1 import javax.swing.*; 2 import javax.swing.table.DefaultTableModel; 3 import java.awt.*; 4 import java.awt.event.ActionEvent; 5 import java.awt.event.ActionListener; 6 7 public class TestJFrame extends JFrame {//窗体类 8 private DefaultTableModel model;//表格模型 9 private JTable table;//表格 10 private JButton addButton, delButton, updButton;//增删改三个按钮 11 private JTextField aTextField, bTextField;//按钮旁边的输入框 12 13 public TestJFrame() {//窗体构造方法 14 setTitle("表格模型"); 15 setBounds(100, 100, 400, 200); 16 setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 17 18 String[] columnNames = {"A", "B"};//定义表格列名 19 String[][] tableValues = {{"A1", "B1"}, {"A2", "B2"}, {"A3", "B3"}};//表格内容 20 21 model = new DefaultTableModel(tableValues, columnNames);//设置模型 22 table = new JTable(model);//引用模型,或table.setModel(model); 23 JScrollPane sc = new JScrollPane(table); 24 //getContentPane().add(sc, BorderLayout.CENTER); 25 add(sc, BorderLayout.CENTER); 26 27 buttonInit();//调用按钮,按钮初始化 28 addMyListener();//组件的监听事件 29 } 30 31 private void buttonInit() { 32 final JPanel panel = new JPanel();//内部默认流布局 33 //getContentPane().add(panel, BorderLayout.SOUTH); 34 add(panel, BorderLayout.SOUTH); 35 panel.add(new JLabel("A:")); 36 aTextField = new JTextField("A4", 5);//文本框的内容和宽度 37 panel.add(aTextField); 38 panel.add(new Label("B:")); 39 bTextField = new JTextField("B4", 5); 40 panel.add(bTextField); 41 addButton = new JButton("增加"); 42 delButton = new JButton("删除"); 43 updButton = new JButton("修改"); 44 panel.add(addButton); 45 panel.add(delButton); 46 panel.add(updButton); 47 } 48 49 private void addMyListener() { 50 addButton.addActionListener(new ActionListener() { 51 public void actionPerformed(ActionEvent e) { 52 String rowData[] = {aTextField.getText(), bTextField.getText()}; 53 model.addRow(rowData);//在表格模型中增加一行内容(文本框内容) 54 int rowCount = table.getRowCount() + 1;//获取当前行数+1 55 aTextField.setText("A" + rowCount);//文本框中内容增1 56 bTextField.setText("B" + rowCount); 57 } 58 }); 59 updButton.addActionListener(new ActionListener() { 60 public void actionPerformed(ActionEvent e) { 61 int selectedRow = table.getSelectedRow();//获取被选中行的索引 62 if (selectedRow != -1) {//存在被选中行 63 model.setValueAt(aTextField.getText(), selectedRow, 0);//修改第1列的值 64 model.setValueAt(bTextField.getText(), selectedRow, 1);//修改第2列的值 65 } 66 } 67 }); 68 delButton.addActionListener(new ActionListener() { 69 public void actionPerformed(ActionEvent e) { 70 int selectedRow = table.getSelectedRow(); 71 if (selectedRow != -1) { 72 model.removeRow(selectedRow);//删除选中的行 73 } 74 } 75 }); 76 } 77 78 public static void main(String[] args) { 79 TestJFrame frame = new TestJFrame(); 80 frame.setVisible(true); 81 } 82 }
结束