Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

java - How to make JTable both AutoResize and horizontall scrollable?

I am putting a JTable into a JScrollPane

But When I set JTable Auto Resizeable, then it won't have horizontal scroll bar.

if I set AUTO_RESIZE_OFF, then the Jtable won't fill the width of its container when the column width is not big enough.

So how can I do this:

  1. when the table is not wide enough, expand to fill its container width
  2. when the table is wide enough, make it scrollable.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to customize the behaviour of the Scrollable interface.

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

public class TableHorizontal extends JFrame
{
    public TableHorizontal()
    {
        final JTable table = new JTable(10, 5)
        {
            public boolean getScrollableTracksViewportWidth()
            {
                return getPreferredSize().width < getParent().getWidth();
            }
        };
        table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );
        final JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
    }

    public static void main(String[] args)
    {
        TableHorizontal frame = new TableHorizontal();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setSize(400, 300);
        frame.setVisible(true);
    }
}

The above code basically sizes the component at its preferred size or the viewport size, whichever is greater.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...