This seems like a newbie question except that I've been trying to wrap my head around the Swing framework for loong time.
Provided you provide an image, dog.jpg, at least 500 px square, the following code should display the image in a scrollpane. If it displayed anything, I probably wouldn't throw my hands up in despair. What am I missing?
import java.awt.BorderLayout;
import javax.swing.*;
public class ScrollSample {
public static void main(String args[]) {
String title = (args.length == 0 ? "JScrollPane Sample" : args[0]);
new ScrollSample( title ) ;
}
public ScrollSample ( String title) {
JFrame frame = new JFrame(title);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Icon icon = new ImageIcon("dog.jpg");
JLabel dogLabel = new JLabel(icon);
dogLabel.setSize( 500, 500 ) ;
JLayeredPane layeredPane = new JLayeredPane() ;
layeredPane.add( dogLabel, new Integer( 0 )) ;
JPanel jp = new JPanel() ;
jp.add( layeredPane ) ;
jp.setSize( 500, 500 ) ;
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(jp);
frame.getContentPane().add( scrollPane, BorderLayout.CENTER);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
Thanks!
You must set the preferred size for JLayeredPane
if you are drawing components of larger widths and sizes to it. Especially since you are adding it to a JPanel with default layout. JLayeredPane
s don't have layout managers by default - so either you manage the bounds or add a preferred layout manager to the layered pane. The simple way would be:
After
JLayeredPane layeredPane = new JLayeredPane() ;
add
layeredPane.setPreferredSize(new Dimension(500,500));
And then maximize your window ( or set your JFrame
's size to 600X600) when the app runs.
Read up on : How to Use Layered Panes