Use absolute layout inside JScrollPane

I need to use a JScrollPane with an absolute layout. I know that using setLayout (null) is not recommended at all. I read that if you want to use the absolute layout with JScrollPane, you must set the preferred element size property inside so that JScrollPane can calculate its size.

I am trying to use the following code to change the order and size of elements, but I cannot figure out where I was wrong.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;


public class frame extends JFrame {

private JPanel contentPane;
private JScrollPane scrollPane;

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                frame frame = new frame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

public frame() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setLayout(null);
    setContentPane(contentPane);

    JPanel panel = new JPanel();
    panel.setBackground(Color.red);
    panel.setBounds(0,0,600,600);
    panel.setPreferredSize(new Dimension(420,280));

    scrollPane = new JScrollPane(panel);
    scrollPane.setBounds(0, 0, 600, 600);
    scrollPane.setLayout(null);
    scrollPane.setBackground(Color.green);

    scrollPane.add(panel);
    scrollPane.setPreferredSize(new Dimension(450,300));
    contentPane.add(scrollPane);
}
}

Why is setPreferredSize not working correctly? Thanks in advance.

+5
source share
3 answers

JScrollPane ; , setLayout(null) (, JPanel), , .

:

  • setLayout(null) JPanel, JScrollPane ( , , ).
  • , JPanel, Scrollable, JScrollPane .
+4

, , ,

-, , JViewport. (scrollPane.add(panel) - , ), scrollPane.setViewportView(panel)

-, Scrollable, .

+5

.

.

panel.setBounds(0,0,600,600);
panel.setPreferredSize(new Dimension(420,280));

scrollPane

scrollPane.setBounds(0, 0, 600, 600);

Well, the borders of the panel are useless, since scrollPane only cares about the preferred size, and the preferred size of the panel is smaller than the borders of scrollPane, so scrollPanel believes that it does not need to show anything otherwise, why it does not show any scrollBars or does not allow them. OBS: I see no reason to set the scrollPanel layout. So you can skip this line.

Just like a comment: Using scroll with an absolute layout panel is just fine, since you care about the preferred panel size.

+2
source

All Articles