Packing a JTable Component

In this section you will learn about the packing of a JTable by adjusting it in the center.

Packing a JTable Component

In this section you will learn about the packing of a JTable by adjusting it in the center.

Packing a JTable Component

Packing a JTable Component

     

In this section you will learn about the packing of  a JTable by adjusting it in the center. 

Description of program:

This program helps you in packing a JTable component. For this you will need a JTable having the data and columns with column headers. To pack the JTable, you will need to apply the getPerferredScrollableVeiwportSize method that returns getPreferredSize.  After doing entire process, you will get the packed JTable that  always be  in center.

Description of code:

getPerrerredScrolllableViewportSize():
This method returns a dimension containing the size of the viewport required for displaying visibleRowCount rows in JTable.

getPreferredSize():
This method returns the preferred size of specified component.

Here is the code of program:

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

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

  public PackJTableComponent(){
  JFrame frame = new JFrame("Packing a JTable Component!");
  JPanel panel = new JPanel();
  String data[][] {{"Vinod","Computer","3"},
  {
"Rahul","History","2"},
  {
"Manoj","Biology","4"},
  {
"Sanjay","PSD","5"}};
  String col [] {"Name","Course","Year"};
  DefaultTableModel model = new DefaultTableModel(data,col);
  table = new JTable(model){
  public Dimension getPreferredScrollableViewportSize() {
  return getPreferredSize();
  }
  };  
  JTableHeader header = table.getTableHeader();
  header.setBackground(Color.yellow);
  JScrollPane pane = new JScrollPane(table);
  panel.add(pane);
  frame.add(panel);
  frame.setSize(300,150);
  frame.setUndecorated(true);
  frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setVisible(true);
  }
}

Download this example.

Output of program: