3

我需要根据标题中的文本获得适当的表格大小。它包含捷克语日期名称的缩写,例如:“Po”、“Út”、“St”、atc。但不是显示这三个点。

我有这个代码:

width, height- 所有最小行/列大小的最大值
allWidth, allHeight- 应该是整个表格的总宽度、高度

//GET DIMENSION
int width = 0;
int height = 0;
int allWidth, allHeight;
for (int col = 0; col < table.getColumnCount(); col++) {        
    TableColumn tableColumn = table.getTableHeader().getColumnModel().getColumn(col);
    TableCellRenderer renderer = tableColumn.getHeaderRenderer();
    if (renderer == null) {
        renderer = table.getTableHeader().getDefaultRenderer();
    }
    Component component = renderer.getTableCellRendererComponent(table,
            tableColumn.getHeaderValue(), false, false, -1, col);
    width = Math.max(component.getPreferredSize().width, width);
    table.getColumnModel().getColumn(col).setPreferredWidth(width);
}
allWidth = table.getColumnCount() * width;
for (int row = 0; row < table.getRowCount(); row++) {
    TableCellRenderer renderer = table.getCellRenderer(row, 0);
    Component comp = table.prepareRenderer(renderer, row, 0);
    height = Math.max(comp.getMinimumSize().height, height);
}
allHeight = table.getRowCount() * height;

//HERE I SET WIDTHS AND HEIGHTS
table.setRowHeight(height);
table.setMinimumSize(new Dimension(allWidth, allHeight));
scrollPane.setMinimumSize(new Dimension(allWidth, allHeight));

我正在使用带有此设置的 GridBagLayout,我认为这没关系:

this.setBorder(BorderFactory.createTitledBorder("Calendar"));
gbc.fill = GridBagConstraints.NONE;
gbc.gridx = 0;
gbc.gridy = 1;   //position x=0, y=0 is for JSpinners, months and years
gbc.weighty = 0;
gbc.weightx = 0;
add(scrollPane,gbc);//add table in a custom Calendar component

我也改变了外观和感觉,这导致了这三个点。否则名称会正确显示。

try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
}

这就是我初始化 JTable 和 JScrollPane 的方式,我觉得这也可以。

    setTable(new JTable());
    getTable().setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    getTable().setAutoscrolls(false);
    getTable().getTableHeader().setResizingAllowed(false);
    getTable().getTableHeader().setReorderingAllowed(false);
    getTable().setColumnSelectionAllowed(true);
    getTable().setRowSelectionAllowed(true);
    getTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    tableModel = new CalendarTableModel();  //my class extended from AbstractTableModel
    getTable().setModel(tableModel);
    scrollPane = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_NEVER,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane.setAutoscrolls(false);

问题:
如果我不使用 gbc 设置 scrollPane 来调整自身大小,除非我手动计算和设置最小大小,否则它会获得最小可能table大小scrollPane。(左图)

使用这个设置,我得到了中间图片的结果,但也太小了。(没有天的名字,高度也有点小。)
我不知道有什么其他更好的方法可以做到这一点,到目前为止我没有找到任何帮助我的方法。

当我考虑一些填充时,例如 2 像素并调整 allWidth,allHeight 的计算,如下所示:

allHeight = (1+table.getRowCount()+pady) * height; //plus one line of header
allWidth = table.getColumnCount() * width;

我得到了右边的图片。

几乎没有桌子 还是太小了 没有帮助

这是一个简单的完整可编译类来演示该问题:

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

public class Main {
    public static void main(String[] args) {
        new Main().start();
    }

    private void start() {
        JFrame f = new JFrame();
        f.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        initTable();

        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
        }

        JPanel calendar = new JPanel();
        calendar.setLayout(new GridBagLayout());
        calendar.setBorder(BorderFactory.createTitledBorder("Calendar"));
        gbc.fill = GridBagConstraints.NONE;
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weighty = 0;
        gbc.weightx = 0;
        calendar.add(scrollPane, gbc);

        f.add(calendar,gbc);

        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }

    JTable table;
    JScrollPane scrollPane;
    CalendarTableModel tableModel;

    private void initTable() {
        setTable(new JTable());
        getTable().setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        getTable().setAutoscrolls(false);
        getTable().getTableHeader().setResizingAllowed(false);
        getTable().getTableHeader().setReorderingAllowed(false);
        getTable().setColumnSelectionAllowed(true);
        getTable().setRowSelectionAllowed(true);
        getTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        tableModel = new CalendarTableModel();  //my class extended from AbstractTableModel
        getTable().setModel(tableModel);
        scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.setAutoscrolls(false);

        //GET DIMENSION
        int width = 0;
        int height = 0;
        int allWidth, allHeight;
        int padx = 2,pady = 2;
        for (int col = 0; col < table.getColumnCount(); col++) {
            TableColumn tableColumn = table.getTableHeader().getColumnModel().getColumn(col);
            TableCellRenderer renderer = tableColumn.getHeaderRenderer();
            if (renderer == null) {
                renderer = table.getTableHeader().getDefaultRenderer();
            }
            Component component = renderer.getTableCellRendererComponent(table,
                    tableColumn.getHeaderValue(), false, false, -1, col);
            width = Math.max(component.getPreferredSize().width, width);
            table.getColumnModel().getColumn(col).setPreferredWidth(width);
        }
        allWidth = (table.getColumnCount()+padx) * width;
        for (int row = 0; row < table.getRowCount(); row++) {
            TableCellRenderer renderer = table.getCellRenderer(row, 0);
            Component comp = table.prepareRenderer(renderer, row, 0);
            height = Math.max(comp.getMinimumSize().height, height);
        }
        allHeight = (1+table.getRowCount()+pady) * height;

//HERE I SET WIDTHS AND HEIGHTS
        table.setRowHeight(height);
        table.setMinimumSize(new Dimension(allWidth, allHeight));
        scrollPane.setMinimumSize(new Dimension(allWidth, allHeight));
    }

    private void setTable(JTable jTable) {
        this.table = jTable;
    }

    private JTable getTable() {
        return this.table;
    }

    private class CalendarTableModel extends AbstractTableModel {
        private String[] daysData = {"Po", "Út", "St", "Čt", "Pá", "So", "Ne"};
        private int[][] values;

        public CalendarTableModel() {
            values = new int[7][6];
            for (int i = 0; i < 6; i++) {
                for (int j = 0; j < 7; j++) {
                    values[j][i] = 7;
                }
            }
        }

        @Override
        public int getRowCount() {
            return 6;
        }

        @Override
        public int getColumnCount() {
            return 7;
        }

        @Override
        public String getColumnName(int column) {
            return daysData[column];
        }

        @Override
        public Object getValueAt(int row, int column) {
            return this.values[column][row];
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    }
}
4

3 回答 3

7

你可以得到这个

在此处输入图像描述

经过

  • f.pack()f.setVisible(true);

  • 所需的宽度应该是 22 / 23 pixelx 但是component.getPreferredSize()或者只返回 17 / 18 并且只为 Po - NeSwingUtilities#computeStringWidth(FontMetrics fm, String str)加上一个像素table.getIntercellSpacing().width

  • 注意真正的解决方法可以基于@camickr 的 TableColumnAdjuster

从代码

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

public class Main {

    public static void main(String[] args) {
        new Main().start();
    }

    private void start() {
        JFrame f = new JFrame();
        f.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        initTable();

        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
        }

        JPanel calendar = new JPanel();
        calendar.setLayout(new GridBagLayout());
        calendar.setBorder(BorderFactory.createTitledBorder("Calendar"));
        gbc.fill = GridBagConstraints.NONE;
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weighty = 0;
        gbc.weightx = 0;
        calendar.add(scrollPane, gbc);
        f.add(calendar, gbc);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }
    JTable table;
    JScrollPane scrollPane;
    CalendarTableModel tableModel;

    private void initTable() {
        setTable(new JTable());
        getTable().setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        getTable().setAutoscrolls(false);
        getTable().getTableHeader().setResizingAllowed(false);
        getTable().getTableHeader().setReorderingAllowed(false);
        getTable().setColumnSelectionAllowed(true);
        getTable().setRowSelectionAllowed(true);
        getTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        tableModel = new CalendarTableModel();  //my class extended from AbstractTableModel
        getTable().setModel(tableModel);
        scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_NEVER, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.setAutoscrolls(false);

        TableColumnModel columnModel = table.getColumnModel();
        for (int col = 0; col < table.getColumnCount(); col++) {
            int maxWidth = 0;
            for (int row = 0; row < table.getRowCount(); row++) {
                TableCellRenderer rend = table.getCellRenderer(row, col);
                Object value = table.getValueAt(row, col);
                Component comp = rend.getTableCellRendererComponent(table, value, false, false, row, col);
                maxWidth = Math.max(comp.getPreferredSize().width, maxWidth);
            }
            TableColumn column = columnModel.getColumn(col);
            TableCellRenderer headerRenderer = column.getHeaderRenderer();
            if (headerRenderer == null) {
                headerRenderer = table.getTableHeader().getDefaultRenderer();
            }
            Object headerValue = column.getHeaderValue();
            Component headerComp = headerRenderer.getTableCellRendererComponent(table, headerValue, false, false, 0, col);
            maxWidth = Math.max(maxWidth, headerComp.getPreferredSize().width);
            // note some extra padding
            column.setPreferredWidth(maxWidth + 6);//IntercellSpacing * 2 + 2 * 2 pixel instead of taking this value from Borders
        }
        DefaultTableCellRenderer stringRenderer = (DefaultTableCellRenderer) table.getDefaultRenderer(String.class);
        stringRenderer.setHorizontalAlignment(SwingConstants.CENTER);
        table.setPreferredScrollableViewportSize(table.getPreferredSize());
    }

    private void setTable(JTable jTable) {
        this.table = jTable;
    }

    private JTable getTable() {
        return this.table;
    }

    private class CalendarTableModel extends AbstractTableModel {

        private String[] daysData = {"Pondelok", "Út", "St", "Čt", "Pá", "Sobota", "Ne"};
        private int[][] values;

        public CalendarTableModel() {
            values = new int[7][6];
            for (int i = 0; i < 6; i++) {
                for (int j = 0; j < 7; j++) {
                    values[j][i] = 30;
                }
            }
        }

        @Override
        public int getRowCount() {
            return 6;
        }

        @Override
        public int getColumnCount() {
            return 7;
        }

        @Override
        public String getColumnName(int column) {
            return daysData[column];
        }

        @Override
        public Object getValueAt(int row, int column) {
            return this.values[column][row];
        }

        @Override
        public boolean isCellEditable(int row, int column) {
            return false;
        }
    }
}
于 2013-08-22T13:31:37.650 回答
2

这是在 JTable 中自动调整标题和单元格内容的绝佳代码:

jTable1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF );

for (int column = 0; column < jTable1.getColumnCount(); column++){
    TableColumn tableColumn = jTable1.getColumnModel().getColumn(column);
    int preferredWidth = tableColumn.getMinWidth();
    int maxWidth = 0;
    TableCellRenderer rend = jTable1.getTableHeader().getDefaultRenderer();
    TableCellRenderer rendCol = tableColumn.getHeaderRenderer();
    if (rendCol == null) rendCol = rend;
    Component header = rendCol.getTableCellRendererComponent(jTable1, tableColumn.getHeaderValue(), false, false, 0, column);
    maxWidth = header.getPreferredSize().width;
    System.out.println("maxWidth :"+maxWidth);

    for (int row = 0; row < jTable1.getRowCount(); row++){
        TableCellRenderer cellRenderer = jTable1.getCellRenderer(row, column);
        Component c = jTable1.prepareRenderer(cellRenderer, row, column);
        int width = c.getPreferredSize().width + jTable1.getIntercellSpacing().width;
        preferredWidth = Math.max(preferredWidth, width);
        System.out.println("preferredWidth :"+preferredWidth);
        System.out.println("Width :"+width);

        //  We've exceeded the maximum width, no need to check other rows

        if (preferredWidth <= maxWidth){
            preferredWidth = maxWidth;
            break;
        }
    }
    tableColumn.setPreferredWidth(preferredWidth);
}
于 2017-03-19T14:59:09.143 回答
1

我找到了解决方案:-)

在计算适当的列宽之前,我必须更改外观。当我反过来做时,计算已经过时了。

所以我只需要像这样设置正确的宽度:

table.getColumnModel().getColumn(col).setPreferredWidth(width);

然后像这样更改视口的大小,因为表的首选大小现在是正确的。

table.setPreferredScrollableViewportSize(table.getPreferredSize());

谢谢!;)

于 2013-08-22T13:46:09.713 回答