Home > OS >  How do you get JTable to extend horizontally beyond the viewport in a JPanel
How do you get JTable to extend horizontally beyond the viewport in a JPanel

Time:11-23

I have a JTable inside of a JPanel with 46 columns. The problem is that you cannot read the headers of the columns, much less any subsequent rows. I haven't been able to easily find a way to extend the table out beyond the viewport, which would allow the scrollbars horizontally. Here is the code I'm using for setting up the table and the viewport for it.

private void setupReferencePanel() {
    refTable = new JTable(null, makeHeaderVector());
    refTable.addMouseListener(new TableListener(presenter));
    refListingPanel = new JPanel();
    refListingPanel.setLayout(new BorderLayout());
    refListingPanel.setBorder(BorderFactory.createTitledBorder("Reference File"));
    refScroller = new JScrollPane(refTable);
    refScroller.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    refTable.setFillsViewportHeight(true);
    //refTable.setFillsViewportWidth(true);
    refListingPanel.add(refScroller, BorderLayout.CENTER);
    refCountLbl = new JLabel("item count: 0");
    refSelect = new SelectionPanel("Selection");
    refListingPanel.add(refSelect, BorderLayout.PAGE_START);
    refListingPanel.add(refCountLbl, BorderLayout.PAGE_END);
    refTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    getContentPane().add(refListingPanel);
}

private Vector makeHeaderVector() {
    String[] cols = { ... }; // hidden array of string contents
    Vector<String> results = new Vector<String>(Arrays.asList(cols));
    return results;
}

CodePudding user response:

I should have set

refTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF) 

instead of

refTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);  

later in the documentation, the constant AUTO_RESIZE_OFF is defined as 'Do not adjust column widths automatically; use a horizontal scrollbar instead.'

  • Related