Java JTable join table column data to String

Description

Java JTable join table column data to String

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

public class Main extends JPanel {
   public static void main(String[] args) {
      JFrame f = new JFrame("JTable");
      f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      f.add(new Main());
      f.pack();/* w ww. j a  va 2s.c o m*/
      f.setVisible(true);
   }

   public Main() {
      TableModel dataModel = new MyTableModel();
      JTable table = new JTable(dataModel);
      
      String i = joinTableColumn(table, 1); 
      System.out.println(i);

      JScrollPane jsp = new JScrollPane(table);
      this.add(jsp);
   }

   public static String joinTableColumn(JTable table, int column) {
      StringBuffer sb = new StringBuffer();
      String s = null;

      for (int i = 0; i < table.getRowCount(); i++) {
          s = (String) table.getValueAt(i, column);
          if (s == null) {
              s = "";
          }
          sb.append(s + ";");
      }
      if (sb.length() > 0) {
          sb.deleteCharAt(sb.length() - 1);
      }
      return sb.toString();
  }
}

class MyTableModel extends AbstractTableModel {

   @Override
   public int getRowCount() {
      return 30;
   }
   @Override
   public String getColumnName(int i) {
      return ""+i;
   }
   @Override
   public int getColumnCount() {
      return 3;
   }

   @Override
   public Object getValueAt(int row, int col) {
      return Math.pow(row, col + 1);
   }

   @Override
   public Class<?> getColumnClass(int col) {
      return getValueAt(0, col).getClass();
   }
}



PreviousNext

Related