简体   繁体   中英

Expanding JTable Inside JFrame

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM