I need to use a JScrollPane with absolute layoute. I know that the use of setLayout(null) is not recommendable at all. I've been reading that if you want to use the absolute layout with a JScrollPane it is necessary to set the preferred size property of the elements inside in order to JScrollPane can calculate its size.
I've been trying the next code changing the order and sizes of elemnts but I can't work out where I've been 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 setPreferredSize is not doing the right work? Thanks in advance.
Changing the layout manager of the actual
JScrollPane
does not make sense; if you wish to use absolute layout within your application you would typically callsetLayout(null)
on a container class (such asJPanel
) in order to position child components within it using absolute positioning.I suggest that you should try:
setLayout(null)
on theJPanel
contained within theJScrollPane
(as I think this is what you're trying to do).JPanel
directly, subclass it and have your subclass implement theScrollable
interface, which provides additional information to theJScrollPane
regarding the optimal scrollable viewport size.