Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing mixing panes

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!

like image 946
Sunny Jim Avatar asked Jul 28 '26 06:07

Sunny Jim


1 Answers

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. JLayeredPanes 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

like image 105
ring bearer Avatar answered Jul 29 '26 21:07

ring bearer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!