Java Swing TableModel get column names

Description

Java Swing TableModel get column names

import java.awt.BorderLayout;
import java.util.Arrays;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;


public class Main extends JPanel {
   public static void main(String[] args) {
      JFrame frame = new JFrame("java2s.com");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      Main m = new Main();
      frame.add(m);//from   w ww  .  jav a  2s.  com
      frame.setSize(300, 210);
      frame.setVisible(true);
   }
   public Main() {
      setLayout(new BorderLayout(5, 5));
      DefaultTableModel model = new DefaultTableModel();

      JTable table = new JTable(model);

      // Add data
      model.addColumn("Col1", new Object[] { "1" });
      model.addColumn("Col2", new Object[] { "2" });

      model.addRow(new Object[] { "a", "b" });
      model.addRow(new Object[] { "c", "d" });

      JScrollPane sp = new JScrollPane(table);

      String[] columns = getColumnNames(table.getModel());
      System.out.println(Arrays.toString(columns));
      
      add(sp, BorderLayout.CENTER);
   }

   public static String[] getColumnNames(TableModel tableModel) {
      int size = tableModel.getColumnCount();
      String[] columnNames = new String[size];
      for (int i = 0; i < size; i++) {
          columnNames[i] = tableModel.getColumnName(i);
      }
      return columnNames;
  }
}



PreviousNext

Related