Jtable with Horizontal Scrollbar

JTable with horizontal scrollbar

First, add your JTable inside a JScrollPane and set the policy for the existence of scrollbars:

new JScrollPane(myTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

Then, indicate that your JTable must not auto-resize the columns by setting the AUTO_RESIZE_OFF mode:

myJTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

How to get horizontal scroll in JTable

To prevent that all columns are resized to the ScrollPane size you can disable the auto resize:

table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

Adding your ScrollPane to the center of the BorderLayout should set the maximum size to the screen size, because normally the JFrame can't become bigger.

To set the size of the ScrollPanes ViewPort to the screen size you can use the awt Toolkit.

table.setPreferredScrollableViewportSize(Toolkit.getDefaultToolkit().getScreenSize());

Horizontal scrollbar is not working with JTable in Java Swing

You need to use:

table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

Don't use:

tab.setPreferredScrollableViewportSize(new Dimension(1,1));

That is an unrealistic size. That method is to give a reasonable preferred size to the table so that the frame.pack() method will work.

js.setPreferredSize(new Dimension(400,400));

Don't set the preferred size of the scrollpane. The setPreferredScrollableViewportSize() is used to specify a size for the table.

mainPanel.setPreferredSize(new Dimension(500, 500));
mainPanel.setSize(500,500);

Don't set a size or a preferred size of a component. Each component is responsible for determining its own preferred size.

mainPanel=new JPanel();

By default a JPanel uses a FlowLayout which means any component added to it is displayed at its preferred size. I would probably set the layout to a BorderLayout. Then the component can resize with the space available and the scrollbars will be used as required.

Edit:

The scrollbars appear when the preferred size of table is greater than the size of the scrollpane. So you need to set the width of the TableColumn based on the width of the text to be displayed in the column. An easy way to do this is to use the Table Column Adjuster class which will set the width to the largest line of text. YOu would invoke this class after you have added the model (containing the data) to the table:

Updated code:

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

public class TableCreate extends JFrame
{
JPanel mainPanel;
TableCreate() throws IOException
{

mainPanel=new JPanel(new BorderLayout());
String InputFile1 = "TableCreate.java";
BufferedReader breader1 = new BufferedReader(new FileReader(InputFile1));
String line1 = "";
line1 = breader1.readLine();

DefaultTableModel model1 = new DefaultTableModel();
model1.addColumn("line");

while((line1=breader1.readLine()) != null)
{
System.out.println(line1);
model1.addRow(new Object[]{line1});
}
breader1.close();

JTable tab=new JTable(model1);

tab.setPreferredScrollableViewportSize(new Dimension(300, 200));
tab.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
TableColumnAdjuster tca = new TableColumnAdjuster(tab);
tca.adjustColumns();

JScrollPane js = new JScrollPane(tab);
add(js);
}

public static void main(String[] args) throws IOException
{
TableCreate tc=new TableCreate();
tc.pack();
tc.setVisible(true);
tc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Jtable columns not horizontally scrollable in NetBeans GUI builder?

As @Andrew Thompson mentiond you should provide some code that addresses the problem. Without seeing your code it's hard to find out what's the problem. But a common workaround about that is as the following:

If you have correctly added your JTable to the ViewPort of a JScrollPane like this:

JTable jtable = new JTable();
//...
JScrollPane sc = new JScrollPane(jtable);
//sc.setViewportView(jtable); <- This way is correct too
//
getContentPane().add(sc);

Then the most probable problem is about the AutoResizeMode of your JTable. Try this:

jtable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

Hope this would help you.

Horizontal scroll bar doesn't work when I add jtable on jscrollpane

Duplicate.

You can find here 2 elegant solutions.

One of which is:

jTable.getParent().addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(final ComponentEvent e) {
if (jTable.getPrefer1sredSize().width < jTable.getParent().getWidth()) {
jTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
} else {
jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
}
}
});

Why does the horizontal scrollbar never show up on JTable?

The solution was to overwrite the getScrollableTracksViewportWidth() method:

@Override
public boolean getScrollableTracksViewportWidth() {
return (getPreferredSize().width < getParent().getWidth());
}

JTable horizontal scrollbar based on width of one column

This is a hackey solution

Basically, what it does is calculates the "preferred" width of all the columns based on the values from all the rows.

It takes into consideration changes to the model as well as changes to the parent container.

Once it's done, it checks to see if the "preferred" width is greater or less than the available space and sets the trackViewportWidth variable accordingly.

You can add in checks for fixed columns (I've not bothered) which would make the process "slightly" faster, but this is going to suffer as you add more columns and rows to the table, as each update is going to require a walk of the entire model.

You could put some kind of cache in, but right about then, I'd be considering fixed width columns ;)

import java.awt.Container;
import java.awt.EventQueue;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JViewport;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

public class TableScrollTest extends JFrame {

public TableScrollTest() {

DefaultTableModel model = new DefaultTableModel(new Object[]{"key", "value"}, 0);
model.addRow(new Object[]{"short", "blah"});
model.addRow(new Object[]{"long", "blah blah blah blah blah blah blah"});

JTable table = new JTable(model) {
private boolean trackViewportWidth = false;
private boolean inited = false;
private boolean ignoreUpdates = false;

@Override
protected void initializeLocalVars() {
super.initializeLocalVars();
inited = true;
updateColumnWidth();
}

@Override
public void addNotify() {
super.addNotify();
updateColumnWidth();
getParent().addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
invalidate();
}
});
}

@Override
public void doLayout() {
super.doLayout();
if (!ignoreUpdates) {
updateColumnWidth();
}
ignoreUpdates = false;
}

protected void updateColumnWidth() {
if (getParent() != null) {
int width = 0;
for (int col = 0; col < getColumnCount(); col++) {
int colWidth = 0;
for (int row = 0; row < getRowCount(); row++) {
int prefWidth = getCellRenderer(row, col).
getTableCellRendererComponent(this, getValueAt(row, col), false, false, row, col).
getPreferredSize().width;
colWidth = Math.max(colWidth, prefWidth + getIntercellSpacing().width);
}

TableColumn tc = getColumnModel().getColumn(convertColumnIndexToModel(col));
tc.setPreferredWidth(colWidth);
width += colWidth;
}

Container parent = getParent();
if (parent instanceof JViewport) {
parent = parent.getParent();
}

trackViewportWidth = width < parent.getWidth();
}
}

@Override
public void tableChanged(TableModelEvent e) {
super.tableChanged(e);
if (inited) {
updateColumnWidth();
}
}

public boolean getScrollableTracksViewportWidth() {
return trackViewportWidth;
}

@Override
protected TableColumnModel createDefaultColumnModel() {
TableColumnModel model = super.createDefaultColumnModel();
model.addColumnModelListener(new TableColumnModelListener() {
@Override
public void columnAdded(TableColumnModelEvent e) {
}

@Override
public void columnRemoved(TableColumnModelEvent e) {
}

@Override
public void columnMoved(TableColumnModelEvent e) {
if (!ignoreUpdates) {
ignoreUpdates = true;
updateColumnWidth();
}
}

@Override
public void columnMarginChanged(ChangeEvent e) {
if (!ignoreUpdates) {
ignoreUpdates = true;
updateColumnWidth();
}
}

@Override
public void columnSelectionChanged(ListSelectionEvent e) {
}
});
return model;
}
};
table.getColumn("key").setPreferredWidth(60);
// table.getColumn("key").setMinWidth(60);
// table.getColumn("key").setMaxWidth(60);
// table.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);

JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}

TableScrollTest frame = new TableScrollTest();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.pack();
frame.setSize(200, 200);
frame.setResizable(true);
frame.setVisible(true);
}
});
}
}

Horizontal Scrolling + JTable + Java

after ranting against the other answers - JXTable (in the SwingX project) has an additional column layout property which

  • fills the horizontal viewport (that is increases the column width) if their combined pref is less than the current width, respecting the autoResizeMode
  • keeps the column sizes at their pref and shows the horizontal scrollbar if their combined pref is greater than the current width

There's a bit of internal tweaking needed, so (biased me) would suggest to use the JXTable. Or have a look at its code and c&p - all allowed, all open source :-)



Related Topics



Leave a reply



Submit