Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <blockquote> <p>..the background image loses his original size and gets very tiny. </p> </blockquote> <p>That is because the preferred size for a panel is 0x0 until components are put in it.</p> <p>There are at least two ways to solve this:</p> <ol> <li>Add content to the panels.</li> <li>Override <code>getPreferredSize()</code> to return the <code>Dimension</code> of the image.</li> </ol> <p>The first is optimal, but I'll show how to do the 2nd (less code).</p> <p><img src="https://i.stack.imgur.com/zVOxE.png" alt="Image Test"></p> <pre><code>import java.awt.*; import java.awt.image.BufferedImage; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; public class ImageTest { public static void main(String[] args) { ImageFrame frame = new ImageFrame(); //frame.setSize(640,480); frame.pack(); frame.setVisible(true); } } class ImagePanel extends JPanel { private Image img; public ImagePanel(String img) { this(new ImageIcon(img).getImage()); } public ImagePanel(Image img) { this.img = img; } public void paintComponent(Graphics g) { super.paintComponent(g); // a panel IS an ImageObserver, so use it here. g.drawImage(img, 0, 0, this); } @Override public Dimension getPreferredSize() { int w = img.getWidth(this); int h = img.getHeight(this); return new Dimension(w,h); } } class ImageFrame extends JFrame { public ImageFrame() { setLayout(new BorderLayout(2,2)); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); ImagePanel topPanel = new ImagePanel(new BufferedImage(200,20,BufferedImage.TYPE_INT_RGB)); ImagePanel bodyPanel = new ImagePanel(new BufferedImage(200,100,BufferedImage.TYPE_INT_RGB)); add(topPanel, BorderLayout.NORTH); add(bodyPanel, BorderLayout.SOUTH); pack(); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload