Moving a Column in JTable

Ads
 

Moving a Column in JTable

This section describes, how to move a column in JTable component.

This section describes, how to move a column in JTable component.

Moving a Column in JTable

     

This section describes, how to move a column in JTable component. Moving is a very simple method  that  moves the data from  one position  to the other. If you want to move a column from one position to another specified position in JTable via using the moveColumn() method,  you need the index of column that will count from '0' which denotes the first column of  JTable. The  moveColumn method  takes the index of columns.

Description of program:

This program helps you in moving a column into  JTable. This program creates a table through the JTable having  '4' rows and '3' columns with the column header and yellow background color in it. This program uses the move method  to move a column at specified position with the help of moveColumn() method. In the first  table, the previous column is Name, secondary  is Course and the third one is Subject. After moving, Course reaches on the first position, Name goes to the second position and Subject does not left it's position  So you can see how the first column  moves from first position to second position.

Here is the code of program:

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;

public class MocveColumn{
  JTable table;
  public static void main(String[] args) {
  new MocveColumn();
  }

  public MocveColumn(){
  JFrame frame = new JFrame("Moveing a column in a JTble");
  JPanel panel = new JPanel();
  String data[][] {{"Vinod","MCA","Computer"},
   {
"Deepak","PGDCA","History"},
   {
"Ranjan","M.SC.","Biology"},
   {
"Radha","BCA","Computer"}};
  String col[] {"Name","Course","Subject"};  
  DefaultTableModel model = new DefaultTableModel(data, col);
  table = new JTable(model);
  //first column move into second position
  move(table, 10);
  JTableHeader header = table.getTableHeader();
  header.setBackground(Color.yellow);
  JScrollPane pane = new JScrollPane(table);
  panel.add(pane);
  frame.add(panel);
  frame.setSize(500,150);
  frame.setUndecorated(true);
  frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
  frame.setVisible(true);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

  public void move(JTable table, int mIndex, int sIndex){
  table.moveColumn(mIndex,sIndex);
  }
}

Download this example.

Output of program:

Initial Table:

After moving a column:

 

Ads

Ads