按百分比设置JTable的列宽

时间:2013-09-25 18:40:18

标签: java swing percentage jtableheader preferredsize

我需要为JTable的几列指定固定宽度,然后为所有其他列指定相等的宽度。

假设JTable有5列。第一列宽度应为100,第二列宽度为150.如果设置两列宽度后JTable的剩余宽度为600,我想将其均匀分割其他三栏。

问题是table.getParent().getSize().width通常为0,即使它已添加到JFrame并且可见,因此我无法将其用作基础。

我该怎么做?

5 个答案:

答案 0 :(得分:11)

public MyJFrame() {
    initComponents();
    resizeColumns();
    addComponentListener(new ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            resizeColumns();
        }
    });
}
//SUMS 1
float[] columnWidthPercentage = {0.2f, 0.55f, 0.1f, 0.05f, 0.05f, 0.05f};

private void resizeColumns() {
    // Use TableColumnModel.getTotalColumnWidth() if your table is included in a JScrollPane
    int tW = jTable1.getWidth();
    TableColumn column;
    TableColumnModel jTableColumnModel = jTable1.getColumnModel();
    int cantCols = jTableColumnModel.getColumnCount();
    for (int i = 0; i < cantCols; i++) {
        column = jTableColumnModel.getColumn(i);
        int pWidth = Math.round(columnWidthPercentage[i] * tW);
        column.setPreferredWidth(pWidth);
    }
}

答案 1 :(得分:5)

  

我需要为JTable的几列分配固定宽度,然后为所有其他列分配相等的宽度。

让桌子的调整大小模式为您完成工作。将调整大小模式设置为所有列,并设置固定列的最小/最大值:

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

public class TableLayout extends JPanel
{
    public TableLayout()
    {
        setLayout( new BorderLayout() );

        JTable table = new JTable(5, 7);
        add( new JScrollPane( table ) );

        table.setAutoResizeMode( JTable.AUTO_RESIZE_ALL_COLUMNS );
        TableColumn columnA = table.getColumn("A");
        columnA.setMinWidth(100);
        columnA.setMaxWidth(100);
        TableColumn columnC = table.getColumn("C");
        columnC.setMinWidth(50);
        columnC.setMaxWidth(50);
    }

    private static void createAndShowUI()
    {
        JFrame frame = new JFrame("TableLayout");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add( new TableLayout() );
        frame.setSize(600, 200);
        frame.setLocationByPlatform( true );
        frame.setVisible( true );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

答案 2 :(得分:3)

我认为您需要使用table.getPreferredSize()。试试这段代码:

import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;


public class Tests {

    private void initGUI(){        
        Object[] tableHeader = new Object[]{"Name", "Category", "Color","Ranking"};
        DefaultTableModel dftm = new DefaultTableModel(tableHeader, 0);        
        dftm.addRow(new Object[]{"Watermelon","Fruit","Green and red",3});
        dftm.addRow(new Object[]{"Tomato","Vegetable","Red",5});
        dftm.addRow(new Object[]{"Carrot","Vegetable","Orange",2});

        JTable table = new JTable(dftm);

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.setViewportView(table);

        Dimension tableSize = table.getPreferredSize();
        table.getColumn("Name").setPreferredWidth(100);
        table.getColumn("Category").setPreferredWidth(150);
        table.getColumn("Color").setPreferredWidth(Math.round((tableSize.width - 250)* 0.70f));
        table.getColumn("Ranking").setPreferredWidth(Math.round((tableSize.width - 250)* 0.30f));

        JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(scrollPane);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                 new Tests().initGUI();
            }
        });        

    }
}

正如您所见,Name列的宽度为100,Category的宽度为150,Color列的宽度为70%{} {1}}最终将达到30%。

<强>更新

基于此评论:

  

谢谢,但如果明确设置了JFrame的大小,这将不起作用   大于JTable ...

解决方案可以使用RankingsetMinWidth方法来修复静态列宽,也可以实现自己的TableColumnModelListener。在上面的示例中,如下所示替换setMaxWidth行,并尝试根据需要设置框架的首选大小:

setPreferredWith

答案 3 :(得分:0)

我必须为必须在不同屏幕分辨率DPI设置上正确显示的项目动态设置我的表列宽度。我的解决方案的想法来自于答案。

基本上我得到了JPanel的首选大小,其中放置了JTable的JSrollPane并且工作得很好。请看下面的

Dimension tableSize =  tableScrollPanePanel.getPreferredSize();
table.getColumnModel().getColumn(0).setPreferredWidth(Math.round(tableSize.width*0.35f));
table.getColumnModel().getColumn(1).setPreferredWidth(Math.round(tableSize.width*0.215f));
table.getColumnModel().getColumn(2).setPreferredWidth(Math.round(tableSize.width*0.20f));
table.getColumnModel().getColumn(3).setPreferredWidth(Math.round(tableSize.width*0.10f));
table.getColumnModel().getColumn(4).setPreferredWidth(Math.round(tableSize.width*0.10f));

希望这有助于某人

由于

答案 4 :(得分:0)

如果我们将它封装在一个自己的类中,它会认为使用(和重用)相对组件大小更容易。由于我也面临同样的问题,我想在这里发布我的代码。

从客户的角度来看,我想做类似的事情

TableColumnModel columnModel = jTable.getColumnModel();

TableColumn firstColumn = columnModel.getColumn(0);
TableColumn secondColumn = columnModel.getColumn(1);

ComponentResize<TableColumn> columnResize = new TableColumnResize();
RelativeWidthResizer<TableColumn> relativeWidthResizer = new RelativeWidthResizer<TableColumn>(columnResize);

relativeWidthResizer.setRelativeWidth(firstColumn, 0.8);
relativeWidthResizer.setRelativeWidth(secondColumn, 0.2);

jTable.addComponentListener(relativeWidthResizer);

所以我首先定义了ComponentResize接口并实现了TableColumnResize

public interface ComponentResize<T> {
    public void setWidth(T component, int width);
}

public class TableColumnResize implements ComponentResize<TableColumn> {

    public void setWidth(TableColumn component, int width) {
        component.setPreferredWidth(width);
    }
}

ComponentResize接口解耦了从具体API设置组件大小的方式。例如。可以通过TableColumn设置setPreferredWidth(int)的宽度,JComponent

可以设置setPreferredWidth(Dimension)的尺寸

我实现了封装相对宽度计算逻辑的RelativeWidthResizer

public class RelativeWidthResizer<T> extends ComponentAdapter {

    private Map<T, Double> relativeWidths = new HashMap<T, Double>();
    private ComponentResize<T> componentResize;

    public RelativeWidthResizer(ComponentResize<T> componentResize) {
        this.componentResize = componentResize;
    }

    public void setRelativeWidth(T component, double relativeWidth) {
        if (relativeWidth < 0.0) {
            throw new IllegalArgumentException(
                    "Relative width must be greater or equal to 0.0");
        }

        if (relativeWidth > 1.0) {
            throw new IllegalArgumentException(
                    "Relative width must be less or equal to 1.0");
        }

        double totalRelativeWidth = 0.0;
        for (Double relativeComponentWidth : relativeWidths.values()) {
            totalRelativeWidth += relativeComponentWidth.doubleValue();
        }

        double availableRelativeWidth = 1.0d - (totalRelativeWidth + relativeWidth);

        boolean totalPercentageExceeded = availableRelativeWidth < 0;
        if (totalPercentageExceeded) {
            double remainingRelativeWidth = 1.0d - totalRelativeWidth;
            String message = MessageFormat.format(
                    "Can't set component's relative width to {0}."
                            + " {1} relative width remaining", relativeWidth,
                    remainingRelativeWidth);
            throw new IllegalArgumentException(message);
        }

        relativeWidths.put(component, relativeWidth);
    }

    @Override
    public void componentResized(ComponentEvent e) {
        Component component = e.getComponent();
        apply(component);
    }

    public void apply(Component baseComponent) {
        Dimension size = baseComponent.getSize();
        int maxWidth = (int) size.getWidth();

        int remaining = maxWidth;

        Set<Entry<T, Double>> entrySet = relativeWidths.entrySet();
        Iterator<Entry<T, Double>> entrySetIter = entrySet.iterator();

        while (entrySetIter.hasNext()) {
            Entry<T, Double> componentEntry = entrySetIter.next();
            T componentToResize = componentEntry.getKey();
            Double relativeWidth = componentEntry.getValue();

            int width = (int) (maxWidth * relativeWidth.doubleValue());
            remaining -= width;

            boolean lastComponent = !entrySetIter.hasNext();
            if (lastComponent && remaining > 0) {
                width += remaining;
            }
            componentResize.setWidth(componentToResize, width);
        }
    }
}