Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There is no concept of a "background image" in a <a href="http://java.sun.com/javase/6/docs/api/javax/swing/JPanel.html" rel="noreferrer"><code>JPanel</code></a>, so one would have to write their own way to implement such a feature.</p> <p>One way to achieve this would be to override the <a href="http://java.sun.com/javase/6/docs/api/javax/swing/JComponent.html#paintComponent(java.awt.Graphics)" rel="noreferrer"><code>paintComponent</code></a> method to draw a background image on each time the <code>JPanel</code> is refreshed.</p> <p>For example, one would subclass a <code>JPanel</code>, and add a field to hold the background image, and override the <code>paintComponent</code> method:</p> <pre><code>public class JPanelWithBackground extends JPanel { private Image backgroundImage; // Some code to initialize the background image. // Here, we use the constructor to load the image. This // can vary depending on the use case of the panel. public JPanelWithBackground(String fileName) throws IOException { backgroundImage = ImageIO.read(new File(fileName)); } public void paintComponent(Graphics g) { super.paintComponent(g); // Draw the background image. g.drawImage(backgroundImage, 0, 0, this); } } </code></pre> <p>(Above code has not been tested.)</p> <p>The following code could be used to add the <code>JPanelWithBackground</code> into a <code>JFrame</code>:</p> <pre><code>JFrame f = new JFrame(); f.getContentPane().add(new JPanelWithBackground("sample.jpeg")); </code></pre> <p>In this example, the <a href="http://java.sun.com/javase/6/docs/api/javax/imageio/ImageIO.html#read(java.io.File)" rel="noreferrer"><code>ImageIO.read(File)</code></a> method was used to read in the external JPEG file.</p>
    singulars
    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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. 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