在GUI中调整JTable中的列

时间:2013-04-27 19:03:21

标签: java swing jtable abstracttablemodel

我有这段代码:

    JPanel textPanel = new JPanel();
    textPanel.setLayout(new GridLayout(0,1));
    //JPanel text = new JPanel();
    //text.setBorder(new TitledBorder(new EtchedBorder(), "Disploay Area"));
    MyModel model = new MyModel();
    //sorter = new TableRowSorter<MyModel>(model);
    final JTable table = new JTable(model);
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    table.setFillsViewportHeight(true);
    table.setAutoCreateRowSorter(true);
    //table.setRowSorter(sorter);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.getSelectionModel().addListSelectionListener(
            new ListSelectionListener() {
                public void valueChanged(ListSelectionEvent event) {
                    int viewRow = table.getSelectedRow();
                    if (viewRow < 0) {
                        //Selection got filtered away.
                        txtstatus.setText("");
                    } else {
                        int modelRow = 
                            table.convertRowIndexToModel(viewRow);
                        txtstatus.setText(
                            String.format("Selected Row in view: %d. " +
                                "Selected Row in model: %d.", 
                                viewRow, modelRow));
                    }
                }
            }
    );
    JScrollPane scroll = new JScrollPane(table);
    scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    scroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
    textPanel.add(scroll, BorderLayout.CENTER);
    c.fill = GridBagConstraints.BOTH;
    c.gridx = 0;
    c.ipadx = 800;
    c.gridy = 1;
    c.ipady = 460;
    c.anchor = GridBagConstraints.CENTER;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.insets = new Insets(0,0,0,0);
    con.add(textPanel, c);

我对我所做的事情感到很困惑,因为我设计的程序是有效的,但如果我想调整一行,那么我可以看到所有信息都会压扁其余部分。无论如何,如果我想重新调整列,它不会影响其余的列吗?

我所做的GUI连接到数据库并检索信息并在JTable中显示。任何帮助将非常感激。

2 个答案:

答案 0 :(得分:3)

您可以使用:

table.setAutoResizeMode( JTable.AUTO_RESIZE_OFF );

现在会根据需要显示水平滚动条。

答案 1 :(得分:3)

看看JTable#setAutoResizeMode

它定义了在更改列大小时应如何调整后续列的大小。

默认情况下,JTable使用AUTO_RESIZE_SUBSEQUENT_COLUMNS