基于一列宽度的JTable水平滚动条 [英] JTable horizontal scrollbar based on width of one column

查看:99
本文介绍了基于一列宽度的JTable水平滚动条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了之前讨论过的问题:获取 JScrollPane 包含 JTable 到按我的意愿显示水平滚动条。 HERE 是我试过的帖子,但由于某些原因它似乎不起作用我的情况(我认为是因为我设置了一个固定宽度的列。

I am running into a problem that has been discussed on here before: getting a JScrollPane containing a JTable to display the horizontal scrollbar as I desire. HERE is a post I tried following, but for some reason it does not seem to work with my situation (I think it is because I've set one of my columns to have a fixed width.

这是一个SSCCE:

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

@SuppressWarnings("serial")
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) {
            public boolean getScrollableTracksViewportWidth() {
                return getPreferredSize().width < getParent().getWidth();
            }
        };        
        table.getColumn("key").setPreferredWidth(60);
        table.getColumn("key").setMinWidth(60);
        table.getColumn("key").setMaxWidth(60);
        table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

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

    public static void main(String[] args) {
        TableScrollTest frame = new TableScrollTest();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setSize(200, 200);
        frame.setResizable(false);
        frame.setVisible(true);
    }
}

简而言之,我有一个用于显示的两列表键/值对。容纳表格的容器具有固定的宽度,并且表格的第一列也具有固定宽度(因为我知道所有键名称将是多长时间)。第二列将包含不同字符串长度的值。只有当存在的值太长而无法适合分配给列的宽度时,才会出现水平滚动条。

In short, I have a two column table for displaying key/value pairs. The container holding the table is of fixed width, and the first column of the table is also of fixed width (since I know how long all the key names will be). The second column will contain values of varying string length. A horizontal scrollbar should only appear when there are values present which are too long to fit in the width allotted for the column.

因为上面的第二个值有这么长的长度,滚动条应该是可见的。然而,事实并非如此,而且我所尝试的一切都只是成功地让它始终可见,这不是我想要的......如果存在长值,我只希望它可见。似乎在表构造函数中重写的 getScrollableTracksViewportWidth()方法检查表的首选宽度是什么......所以我需要指导表更喜欢基于第二列内容的更大宽度......但是我很难过。

Because the second value above has such a long length, the scrollbar should be visible. However, it's not, and everything I have tried has only succeeded in getting it visible always, which is not what I want... I only want it visible if "long" values are present. It seems like the getScrollableTracksViewportWidth() method being overridden in the table constructor checks what the preferred width of the table is... so somehow I need to direct the table to prefer a larger width based on the contents of that second column only... but I'm stumped.

任何想法?

推荐答案

这是一个hackey解决方案

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.

一旦完成,它会检查首选宽度是否大于或小于可用空间,并相应地设置 trackViewportWidth 变量。

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);
            }
        });
    }
}

这篇关于基于一列宽度的JTable水平滚动条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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