How to Display JTable with Horizontal and Vertical Scrollbars

                                      JTable is a one of the most important and useful component in Java Swings.
Some scenarios we need both Horizontal and Vertical Scrollbars in JTable.
 Below code help you display Horizontal and Vertical Scrollbars in JTable.

import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

class JTableScrollPane extends JFrame {
Vector columns = new Vector();
static Vector

public JTableScrollPane() {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
JTable table = new JTable();
String[] columnNames = { “Column1”, “Column2” };
addColumns(columnNames);
DefaultTableModel defaulttablemodel = new DefaultTableModel();

for (int i = 0; i < 60; i++) {
Vector vect = new Vector();
vect.addElement(“test”);
rows.addElement(vect);

}

defaulttablemodel.setDataVector(rows, columns);
table.setModel(defaulttablemodel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
int vColIndex = 1;
TableColumn col = table.getColumnModel().getColumn(vColIndex);
int width = 400;
col.setPreferredWidth(width);

JScrollPane scroll = new JScrollPane(table, v, h);
scroll.setViewportView(table);

scroll.setAutoscrolls(true);
panel.add(scroll);
frame.add(panel);
frame.setSize(500, 500);
frame.setVisible(true);

}

private void addColumns(String[] colName)// Table Columns
{
for (int i = 0; i < colName.length; i++)
columns.addElement(colName[i]);
}

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

About mohan

This is Mohan Jayapalan author of TechPages Blog.I am a part time blogger and Currently working for private Software Concern.

© Copyright 2010-2016 www.techpages.org · All Rights Reserved · Powered by WordPress ·