Expanding JTable Inside JFrame

会有一股神秘感。 提交于 2020-01-04 05:29:18

问题


I have the following layout that looks like this:

But I would like the table at the top to be minimized to just the headers, then grow vertically as clients are added. How do I go about doing this? Here is the code currently......

JFrame frame;
JTable clientTable;
DefaultTableModel clientTableModel;
JTextArea messageArea;

...

String[] tableColumnNames = ...
Object[][] data = ...

Toolkit toolkit =  Toolkit.getDefaultToolkit ();
Dimension dim = toolkit.getScreenSize();

frame = new JFrame("Server");

clientTableModel = new DefaultTableModel(0, 0);
clientTableModel.setColumnIdentifiers(tableColumnNames);

clientTable = new JTable(data, tableColumnNames);
clientTable.setPreferredScrollableViewportSize(new Dimension(dim.width-30, 82));
clientTable.setFillsViewportHeight(true);
clientTable.setModel(clientTableModel);

messageArea = new JTextArea(8, 40);
messageArea.setEditable(false);
DefaultCaret caret = (DefaultCaret) messageArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);      

frame.getContentPane().add(new JScrollPane(clientTable), "North");
frame.getContentPane().add(new JScrollPane(messageArea), "Center");
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); 

回答1:


Each time you invoke pack(), the enclosing Window will be "sized to fit the preferred size and layouts of its subcomponents." Override getPreferredScrollableViewportSize() and return a suitable multiple of the row height. In the fragment below, N is the number of rows after which you want the scrollbar to appear.

JTable table = new JTable(tableModel) {

    @Override
    public Dimension getPreferredScrollableViewportSize() {
        int h = Math.min(N, table.getRowCount());
        return new Dimension(dim.width - 30, table.getRowHeight() * h);
    }
};

When you add a new row, invoke pack(), and the enclosing Window will adopt the new size. This related example illustrates the effect for a JList.



来源:https://stackoverflow.com/questions/33788172/expanding-jtable-inside-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!