JTable not showing

若如初见. 提交于 2019-11-26 10:49:28

Invoking setModel() on the table should be sufficient, but you might call fireTableStructureChanged() on the model explicitly as a way to help sort things out.

Also, verify that you are working on the event dispatch thread.

Addendum: Here's an sscce that shows the basic approach.

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

/** @see http://stackoverflow.com/questions/8257148 */
public class SwapTableModel extends JPanel {

    public SwapTableModel() {
        final JTable table = new JTable(Model.Alpha.model);
        table.setPreferredScrollableViewportSize(new Dimension(128, 32));
        this.add(new JScrollPane(table));
        final JComboBox combo = new JComboBox();
        for (Model model : Model.values()) {
            combo.addItem(model);
        }
        this.add(combo);
        combo.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Model model = (Model) combo.getSelectedItem();
                table.setModel(model.model);
            }
        });
    }

    private enum Model {

        Alpha(), Beta();
        private DefaultTableModel model;

        private Model() {
            Object[] data = {this.toString()};
            this.model = new DefaultTableModel(data, 1);
            model.addRow(data);
        }
    }

    private void display() {
        JFrame f = new JFrame("SwapTableModel");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new SwapTableModel().display();
            }
        });
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!