如何使JTable既可自动调整大小又可水平滚动? [英] How to make JTable both AutoResize and horizontall scrollable?

查看:114
本文介绍了如何使JTable既可自动调整大小又可水平滚动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将JTable放入JScrollPane

I am putting a JTable into a JScrollPane

但是当我设置JTable Auto Resizeable时,它将没有水平滚动条.

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

如果我设置了AUTO_RESIZE_OFF,那么当列宽不够大时,Jtable将不会填充其容器的宽度.

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.

那我该怎么做:

  1. 当桌子不够宽时,展开以填充其容器宽度
  2. 当表足够宽时,使其可滚动.

谢谢

推荐答案

您需要自定义Scrollable接口的行为.

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.

这篇关于如何使JTable既可自动调整大小又可水平滚动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆