日期:2014-05-20 浏览次数:20844 次
/** * <br>Created on 2010-11-11 * @author Alex.Huang */ package ext.test.jws.gui; import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.Toolkit; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; /** * <br>Created on 2010-11-11 * @author Alex.Huang */ public class PanelImageTest extends JPanel { private Image image; public PanelImageTest() { super(); setOpaque(true); image = Toolkit.getDefaultToolkit().getImage( "D:/My Document/My Pictures/Wallpaper Images/NOAA/line0053.jpg"); ; } public void paintComponent(Graphics g) { super.paintComponent(g); setBackground(Color.WHITE); if (image != null) { int height = image.getHeight(this); int width = image.getWidth(this); if (height != -1 && height > getHeight()) height = getHeight(); if (width != -1 && width > getWidth()) width = getWidth(); int x = (int) (((double) (getWidth() - width)) / 2.0); int y = (int) (((double) (getHeight() - height)) / 2.0); g.drawImage(image, x, y, width, height, this); } } public static void main(String[] args) { JFrame frame=new JFrame(); PanelImageTest panel=new PanelImageTest(); JButton b=new JButton("按钮"); panel.add(b); frame.add(panel); frame.setVisible(true); } }
------解决方案--------------------
import java.awt.Graphics; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class Background extends JFrame{ ImageIcon image; JLabel imageLabel; JPanel backgroundPane; public Background() { image = new ImageIcon(Background.class.getClassLoader().getResource("images/background.gif")); backgroundPane = new JPanel(); imageLabel = new JLabel(image); backgroundPane.add(imageLabel); this.add(backgroundPane); this.setBounds(200, 300, 381, 330); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void paint(Graphics g) { g.drawImage(image.getImage(), 0, 20, this); } public static void main(String[] args) { Background bg = new Background(); } }