You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于AbstractTableModel为JTable添加行?实现按钮触发与内部监听器逻辑

How to Add Text Field Data to JTable with AbstractTableModel and Inner Listener

Got it, let's walk through a complete, working implementation of what you're trying to do. Using an inner listener class with a custom AbstractTableModel is a solid approach—here's how to pull it off step by step:

Step 1: Create a Custom AbstractTableModel Subclass

First, we'll build our own table model to manage the data. This is where we'll handle storing rows and notifying the table view when data changes (critical for updating the JTable automatically).

import javax.swing.table.AbstractTableModel;
import java.util.ArrayList;
import java.util.List;

class CustomTableModel extends AbstractTableModel {
    // Define your table columns (adjust names/number as needed)
    private final String[] columnNames = {"Entered Data"};
    // Store table rows in a list for easy manipulation
    private final List<String> tableRows = new ArrayList<>();

    @Override
    public int getRowCount() {
        return tableRows.size();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public String getColumnName(int column) {
        return columnNames[column];
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        // Return the data for the requested row/column
        return tableRows.get(rowIndex);
    }

    // Custom method to add a new row to the model
    public void addNewRow(String data) {
        // Optional: Add validation to skip empty/blank inputs
        if (data != null && !data.trim().isEmpty()) {
            tableRows.add(data.trim());
            // Notify the table that a new row was inserted (triggers UI update)
            fireTableRowsInserted(tableRows.size() - 1, tableRows.size() - 1);
        }
    }
}

Step 2: Build the UI and Inner Listener Class

Next, we'll create the main window with the text field, "Add new" button, and JTable. The inner listener class will handle button clicks, pull data from the text field, and pass it to our custom model.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TableRowAdder extends JFrame {
    private JTextField inputTextField;
    private CustomTableModel tableModel;

    public TableRowAdder() {
        setTitle("Add Rows to JTable");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(450, 350);
        setLayout(new BorderLayout());

        // Create top panel with input field and button
        JPanel inputPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 10));
        inputTextField = new JTextField(25);
        JButton addButton = new JButton("Add new");
        
        // Attach our inner listener to the button
        addButton.addActionListener(new AddButtonClickListener());

        inputPanel.add(inputTextField);
        inputPanel.add(addButton);
        add(inputPanel, BorderLayout.NORTH);

        // Create table with our custom model
        tableModel = new CustomTableModel();
        JTable dataTable = new JTable(tableModel);
        add(new JScrollPane(dataTable), BorderLayout.CENTER);

        setVisible(true);
    }

    // Inner listener class to handle button click events
    private class AddButtonClickListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // Grab text from the input field
            String inputData = inputTextField.getText();
            // Pass the data to the table model to add a new row
            tableModel.addNewRow(inputData);
            // Clear the text field and refocus for next input
            inputTextField.setText("");
            inputTextField.requestFocus();
        }
    }

    public static void main(String[] args) {
        // Always run Swing UI code on the Event Dispatch Thread
        SwingUtilities.invokeLater(TableRowAdder::new);
    }
}

Key Details to Remember:

  • Model-View Separation: The CustomTableModel handles all data logic, while the UI code focuses on user interaction—this keeps your code clean and maintainable.
  • Fire Events: The fireTableRowsInserted method is mandatory! It tells the JTable to refresh its view to display the new row. Without this, the table won't update even if the model's data changes.
  • Inner Class Benefit: The inner AddButtonClickListener can directly access the outer class's inputTextField and tableModel variables, so you don't need messy workarounds like passing references or using static variables.
  • Input Validation: The addNewRow method skips blank inputs—you can expand this logic to validate specific data formats (like numbers, emails) if needed.

Just compile and run this code, type text into the field, click "Add new", and you'll see the row appear in the table instantly.

内容的提问来源于stack exchange,提问作者Andrew Quinn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:25:12