JScrollPane not working in null layout

后端 未结 2 1163
野趣味
野趣味 2021-01-27 23:26
  import javax.swing.JCheckBox;
  import javax.swing.JFrame;
  import javax.swing.JLabel;
  import javax.swing.JPanel;
  import javax.swing.JScrollPane;

public class Sc         


        
2条回答
  •  盖世英雄少女心
    2021-01-28 00:09

    I see OP already set desired/correct answer for him, yet that solution does not work with dynamic content (in my case vertically on Y axis) so I "repaired" or updated - if you will - Mateusz's original answer so that now it actually works even with dynamic JPanel content (like when you adding to it other components on the run which was my case).

    Here is my code (works, using it myself):

    import java.awt.Component;
    import java.awt.Dimension;
    
    import javax.swing.JPanel;
    
    public class JPanelForNullLayoutScroll extends JPanel {
    
        int h;
    
        @Override
        public Dimension getPreferredSize() {
    
            if (getComponentCount() > 0) {
                h = 0;
    
                for (Component c : getComponents()) {
                    h += c.getHeight();
                }
    
            } else {
                h = 0;
            }
    
            // as I do not need width recount
            //I set it to be taken directly from the component itself
            Dimension d = new Dimension(getWidth(), h);
    
            return d;
        }
    
    }
    

    You can use it then in your code by implementing it like:

    int tableW = 300;
    int tableH = 300;
    
    // JPANEL WITH NULL LAYOUT
    JPanelForNullLayoutScroll container = new JPanelForNullLayoutScroll();
    container.setLayout(null);
    container.setVisible(true);
    container.setEnabled(true);
    container.setBounds(0, 0, tableW, tableH);
    
    // SCROLLER
    JScrollPane scrollPane = new JScrollPane(container);
    scrollPane.setAlignmentX(JLabel.LEFT_ALIGNMENT);
    scrollPane.getVerticalScrollBar().setUnitIncrement(8);
    scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setBounds(0, 0, tableW, tableH);
    

提交回复
热议问题