123 發問時間: 電腦與網際網路程式設計 · 7 年前

java ------- table 資料刪除

編譯軟體 : NetBeans IDE 7.3.1

語言: Java

int column = Integer.valueOf(jTextField6.getText());

int row = Integer.valueOf(jTextField7.getText());

DefaultTableModel tableModel = (DefaultTableModel) jTable1.getModel();

tableModel.removeRow(column);

jTable1.removeColumn(jTable1.getColumnModel().getColumn(row));

不管我輸入第幾欄第幾列,他都只會刪第1欄或第1列,請問我該如何修改

已更新項目:

請各位前輩幫幫忙 感謝了

1 個解答

評分
  • John
    Lv 7
    7 年前
    最佳解答

    try this...

    import javax.swing.*;

    import javax.swing.table.*;

    import java.awt.*;

    import java.awt.event.*;

    public class Program extends JFrame {

    private JTable table;

    private JTextField txtRow, txtColumn;

    private JButton btnDelete;

    public static void main(String[] args) {

    new Program();

    }

    public Program() {

    JPanel pane = new JPanel();

    table = buildTable();

    pane.add(new JScrollPane(table));

    pane.add(new JLabel("Row?"));

    txtRow = new JTextField(5);

    pane.add(txtRow);

    pane.add(new JLabel("Column?"));

    txtColumn = new JTextField(5);

    pane.add(txtColumn);

    btnDelete = new JButton("Delete");

    btnDelete.addActionListener(btnDeleteOnClick);

    pane.add(btnDelete);

    add(pane);

    setTitle("Table Deletion");

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setSize(300, 300);

    setVisible(true);

    }

    private final ActionListener btnDeleteOnClick = new ActionListener() {

    @Override

    public void actionPerformed(ActionEvent e) {

    int row = parseAsInteger(txtRow);

    int col = parseAsInteger(txtColumn);

    DefaultTableModel dtm = (DefaultTableModel) table.getModel();

    if (col >= 0 && row >= 0) {

    dtm.setValueAt(null, row, col);

    } else if (col >= 0) {

    TableColumn tblColumn = table.getColumnModel().getColumn(col);

    table.removeColumn(tblColumn);

    } else if (row >= 0) {

    dtm.removeRow(row);

    }

    }

    };

    private JTable buildTable() {

    Object[][] data = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

    String[] columns = {"Column A", "Column B", "Column C"};

    DefaultTableModel dtm = new DefaultTableModel(data, columns);

    JTable table = new JTable();

    table.setModel(dtm);

    table.setPreferredScrollableViewportSize(new Dimension(250, 150));

    return table;

    }

    private int parseAsInteger(JTextField txt) {

    int result = -1;

    try {

    result = Integer.parseInt(txt.getText());

    } catch (NumberFormatException ignore) {

    }

    return result;

    }

    }

還有問題?馬上發問,尋求解答。