Home Java Example Java Swing Appending a Column in JTable



Appending a Column in JTable
Posted on: April 14, 2007 at 12:00 AM
In this section, you will see how to add a new column in JTable.

Appending a Column in JTable

     

In this section, you will see how to add a new column in JTable. For adding a new column in JTable component you have to need a table model that supports this operations to use some Java methods and APIs.

Description of program:

In this program, we will see how to add (append) a new column in JTable. The following program creates a table that contains some data and columns with headers. When it runs first time, it displays a table with three columns and when you will run this program again after removing the comments, you will see the following results. An added column will be displays on the the screen in a JTable. Try it and see the result. 

Description of code:

addColumn(Object col_name):
This is the method that is used to add a new column to the model. It takes column name which have to added in a table.

Here is the code of program:

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

public class AppendColumn{
  public static void main(String[] args) {
  new AppendColumn();
  }

  public AppendColumn(){
  JFrame frame = new JFrame("Appending Column Example!");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  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);
//  model.addColumn("Grade");
  JTable table = new JTable(model);
  JTableHeader header = table.getTableHeader();
  header.setBackground(Color.yellow);
  JScrollPane pane = new JScrollPane(table);
  panel.add(pane);
  frame.add(panel);
  frame.setUndecorated(true);
  frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
  frame.setSize(500,150);
  frame.setVisible(true);
  }
}

 

 

 

 

 

 

 

Download this example.

Output of program:

Before Appending a column:

After Appending a column:

Related Tags for Appending a Column in JTable:
javacswingtabledataheadercolumnheadersjtablevicolumnsappendidaiappcreatetabexamplewithprogramramcontainsexamjtaeitpeinmheadntjadesendpenmeproppumnxaxampssocolathallmplfolloweaandwingvassthswavabablaphatendsendslumpleplprndonomogrolo


More Tutorials from this section

Ask Questions?    Discuss: Appending a Column in JTable   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.