JTable inside JScrollPane: best height to disable scrollbars

后端 未结 3 1450
粉色の甜心
粉色の甜心 2020-12-04 00:57

I am using the following code to create JTable inside JScrollPane to show column headers

JTable won't show column headers



        
3条回答
  •  醉梦人生
    2020-12-04 01:17

    The basic approach is

    • JTable is-a Scrollable which unfortunately doesn't do too well in calculating a prefScrollable, so you have to do it yourself
    • either use a LayoutManager which lays out all at their pref (f.i. FlowLayout), or implement max in JTable (if you use a resizing but max-respecting manager like BoxLayout)
    • JScrollPane is-a validationRoot, so the revalidate must happen on the parent of the scrollPane

    Something like:

    final JTable table = new JTable(10, 5) {
    
        @Override
        public Dimension getPreferredScrollableViewportSize() {
            Dimension dim = super.getPreferredScrollableViewportSize();
            // here we return the pref height
            dim.height = getPreferredSize().height;
            return dim;
        }
    
    };
    final JComponent content = new JPanel();
    content.add(new JScrollPane(table));
    Action add = new AbstractAction("add row") {
    
        @Override
        public void actionPerformed(ActionEvent e) {
            ((DefaultTableModel) table.getModel()).addRow(new Object[]{});
            content.revalidate();
        }
    };
    

提交回复
热议问题