JTable with horizontal scrollbar

爱⌒轻易说出口 提交于 2019-11-26 16:32:20

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);
Nitesh Verma

Set the AutoResizeMode to OFF in the properties of the jTable

trashgod

For reference, here's a minimal example of the accepted approach. Moreover,

import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;

/**
 * @see https://stackoverflow.com/a/37318673/230513
 */
public class Test {

    private void display() {
        JFrame f = new JFrame("Test");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        TableModel model = new AbstractTableModel() {
            private static final int N = 32;

            @Override
            public int getRowCount() {
                return N;
            }

            @Override
            public int getColumnCount() {
                return N;
            }

            @Override
            public Object getValueAt(int rowIndex, int colIndex) {
                return "R" + rowIndex + ":C" + colIndex;
            }
        };
        JTable table = new JTable(model) {
            @Override
            public Dimension getPreferredScrollableViewportSize() {
                return new Dimension(320, 240);
            }
        };
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        f.add(new JScrollPane(table));
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Test()::display);
    }
}

For me it works:

table.setAutoscrolls(true);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!