简体   繁体   English

如何在JFrame中使用ActionListener刷新JTable?

[英]How do I refresh JTable with ActionListener in JFrame?

I want to refresh two dimensional array table in my JFrame with ActionListener . 我想用ActionListener刷新JFrame二维数组表。 Here is some codes from my program: 这是我程序中的一些代码:

public Students(){
     .....
     removeall = new JMenuItem("Remove All Students");
     removeall.addActionListener(this);
     .....
}
public void actionPerformed(ActionEvent e) {

    if(e.getSource().equals(removeall)) {
        removeAll();
        table.repaint();
}

public void removeAll() {

    for(int i=name1.size()-1;i>=0;i--) 
    {
        lastname1.remove(i);
        id1.remove(i);
        quiz11.remove(i);
        quiz21.remove(i);
        midterm1.remove(i);
        project1.remove(i);
        final1.remove(i);
        lettergrade1.remove(i);
        average1.remove(i);
        name1.remove(i);
        tablemodel.removeRow(i);
    }
    JOptionPane.showMessageDialog(this,"All students are removed. ");
}

As you see, I have tried repaint() and tableModel.fireTableDataChanged() and both of them didn't work. 如您所见,我尝试了repaint()tableModel.fireTableDataChanged() ,但它们都没有起作用。 What should I do to refresh my table? 我应该怎么做才能刷新我的桌子? And also here is a picture: 这也是一张图片:

It doesn't refresh: 它不会刷新:

它不刷新

Your question is impossible to answer precisely since you haven't posted a valid MCVE for us to compile and run, but it looks like you're trying to change the state of a collection that was used to initialize a JTable's model without changing the actual model itself. 由于您尚未发布有效的MCVE供我们编译和运行,因此无法准确回答您的问题,但是您似乎在尝试更改用于初始化JTable模型的集合的状态,而无需更改实际的模型本身。

Having said that, to remove all the data from a JTable, remove all the rows. 话虽如此,要删除JTable中的所有数据,请删除所有行。 If you're using a DefaultTableModel, then this means simply calling .setRowCount(0) on the model. 如果使用的是DefaultTableModel,则意味着只需在模型上调用.setRowCount(0)

Note that there is no need to call repaint() in this situation since by changing the model, repaint is automatically called. 请注意,在这种情况下无需调用repaint() ,因为通过更改模型,将自动调用repaint。 Also your code shouldn't even attempt to call fireTableDataChanged() on the model, since this type of call should be called internally by the model itself only. 同样,您的代码甚至都不应该尝试在模型上调用fireTableDataChanged() ,因为这种类型的调用只能由模型本身在内部进行调用。

For example, my MCVE: 例如,我的MCVE:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Random;
import javax.swing.*;
import javax.swing.table.*;

public class TableExample {
    private static void createAndShowGui() {
        TablePanel tablePanel = new TablePanel();
        JMenuItem fillTableItem = new JMenuItem(new FillTableAction(tablePanel));
        JMenuItem clearTableItem = new JMenuItem(new ClearTableAction(tablePanel));

        JMenu tableMenu = new JMenu("Table Actions");
        tableMenu.setMnemonic(KeyEvent.VK_T);
        tableMenu.add(fillTableItem);
        tableMenu.add(clearTableItem);
        JMenuBar menuBar = new JMenuBar();
        menuBar.add(tableMenu);

        JFrame frame = new JFrame("TableExample");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(tablePanel);
        frame.setJMenuBar(menuBar);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

@SuppressWarnings("serial")
class FillTableAction extends AbstractAction {
    private TablePanel tablePanel;

    public FillTableAction(TablePanel tablePanel) {
        super("Fill Table");
        putValue(MNEMONIC_KEY, KeyEvent.VK_F);
        this.tablePanel = tablePanel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        tablePanel.fillTable();
    }
}

@SuppressWarnings("serial")
class ClearTableAction extends AbstractAction {
    private TablePanel tablePanel;

    public ClearTableAction(TablePanel tablePanel) {
        super("Clear Table");
        putValue(MNEMONIC_KEY, KeyEvent.VK_C);
        this.tablePanel = tablePanel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        tablePanel.clearTable();
    }
}

@SuppressWarnings("serial")
class TablePanel extends JPanel {
    private static final String[] COL_NAMES = { "Name", "Surname", "ID" };
    private DefaultTableModel model = new DefaultTableModel(COL_NAMES, 0);
    private JTable table = new JTable(model);
    private Random random = new Random();

    public TablePanel() {
        setLayout(new BorderLayout());
        add(new JScrollPane(table));
    }

    public void clearTable() {
        model.setRowCount(0);
    }

    // fill it with random text and data
    public void fillTable() {
        int rows = random.nextInt(50) + 40;
        for (int i = 0; i < rows; i++) {
            StringBuilder sb = new StringBuilder();
            char c = (char) ('A' + random.nextInt(26));
            sb.append(c);
            for (int j = 0; j < 4 + random.nextInt(3); j++) {
                sb.append((char) ('a' + random.nextInt(26)));
            }
            String name = sb.toString();

            sb.delete(0, sb.length());
            sb.append((char) ('A' + random.nextInt(26)));
            for (int j = 0; j < 6 + random.nextInt(4); j++) {
                sb.append((char) ('a' + random.nextInt(26)));
            }
            String surName = sb.toString();

            int id = random.nextInt(Integer.MAX_VALUE / 2);

            Object[] rowData = { name, surName, id };
            model.addRow(rowData);
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM