I am trying to add a jpeg as a packground to my JFrame. I have read quite a few posts on how to do it in here, but none seem to work . Has anybody tried this and goit it working? If so some tips would be good.
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
publicclass BackgroundImage extends JFrame
{
JScrollPane scrollPane;
ImageIcon icon;
Image image;
public BackgroundImage()
{
icon = new ImageIcon("???.jpg");
JPanel panel = new JPanel()
{
protectedvoid paintComponent(Graphics g)
{
// Dispaly image at at full size
g.drawImage(icon.getImage(), 0, 0, null);
// Scale image to size of component
// Dimension d = getSize();
// g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);
// Fix the image position in the scroll pane
// Point p = scrollPane.getViewport().getViewPosition();
// g.drawImage(icon.getImage(), p.x, p.y, null);
super.paintComponent(g);
}
};
panel.setOpaque( false );
panel.setPreferredSize( new Dimension(400, 400) );
scrollPane = new JScrollPane( panel );
getContentPane().add( scrollPane );
JButton button = new JButton( "Hello" );
panel.add( button );
}
publicstaticvoid main(String [] args)
{
BackgroundImage frame = new BackgroundImage();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}
I've also been playing around with an ImagePanel which allows you do to much the same thing without overriding any methods. Its just got some basic funtionality, but you may find it usefull:
I have a problem with background image when i use internal frames.
I use a JDesktopPane which i puts into a container (Which has the ContentPane of the frame) and my internal frames are not displayed (Only the buttons and the textfields are displayed).
Since you have customized the code we don't know what your are doing.
So create your own postiing (no need to clutter this posting) and post your own demo code. That is, create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program[/url] (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
Don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags[/url] so the posted code retains its original formatting.
I have a question about this piece. Im guessing you are overriding the method as soon as you create the object.
Is that whats going on?
JPanel panel = new JPanel()
{
protectedvoid paintComponent(Graphics g)
{
// Dispaly image at at full size
g.drawImage(icon.getImage(), 0, 0, null);
// Scale image to size of component
// Dimension d = getSize();
// g.drawImage(icon.getImage(), 0, 0, d.width, d.height, null);
// Fix the image position in the scroll pane
// Point p = scrollPane.getViewport().getViewPosition();
// g.drawImage(icon.getImage(), p.x, p.y, null);
super.paintComponent(g);
}
};