Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

JPanel with background image.

843785Oct 3 2008 — edited Oct 4 2008
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Paint;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;

public class ScalePanel extends JPanel {

//public static JFrame frame = null;

public ScalePanel(Image bgImage) {
this.bgImage = bgImage;
}

Image bgImage;

public void paintComponent(Graphics g) {
double scaleX = this.getWidth() / (double) bgImage.getWidth(null);
double scaleY = this.getHeight() / (double) bgImage.getHeight(null);
AffineTransform xform = AffineTransform.getScaleInstance(scaleX,
scaleY);
((Graphics2D) g).drawImage(bgImage, xform, this);
}
public static void main(String[] args) {
//set up style variables
Dimension d = new Dimension(640, 480);
Color grey = new Color(210,210,210);
BufferedImage img = new BufferedImage(500, 200, BufferedImage.TYPE_INT_ARGB);

//background gfx
Graphics2D g = img.createGraphics();
Paint paint = new GradientPaint(0, 0, grey, 125, 0, Color.white);
Paint paint2 = new GradientPaint(375, 0, Color.white, 500, 0, grey);
g.setPaint(paint);
g.fillRect(0, 0, 250, 200);
g.setPaint(paint2);
g.fillRect(250,0,500,200);
g.dispose();

//create main window
ScalePanel sp = new ScalePanel(img);
JLayeredPane layerPane = new JLayeredPane();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//create GUI
JPanel panel1=new JPanel();
frame.getContentPane().add(sp);
createGUI.addText(frame);
frame.setMinimumSize(d);
frame.pack();
frame.show();
}
}
This code makes a window that has a realizable gradient background. It works fine but when i try to add components such as a JLabel or a button the background is no longer visible. Any Ideas?
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 1 2008
Added on Oct 3 2008
7 comments
524 views