像这样?
附录:“通常您会
super.paintComponent(g)先调用,但是由于图像将覆盖整个背景,因此无需这样做。” —
[camickr]
如果仅创建自定义UI来添加背景图像,则更简单的方法是对JDesktopPane进行自定义绘制,以使其适用于所有LAF:
JDesktopPane desktop = new JDesktopPane(){ protected void paintComponent(Graphics g) { g.drawImage(image, 0, 0, getWidth(), getHeight(), null); }};通常,您将首先调用super.paintComponent(g),但是由于图像将覆盖整个背景,因此无需执行此操作。
附录:另请参见opacity属性。
import java.awt.Dimension;import java.awt.EventQueue;import java.awt.Graphics;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import javax.imageio.ImageIO;import javax.swing.Jframe;import javax.swing.JLabel;import javax.swing.JPanel;public class Imager { public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { Jframe frame = new Jframe(); frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); frame.add(new ImagePanel("image.jpg")); frame.pack(); frame.setVisible(true); } }); } private static class ImagePanel extends JPanel { BufferedImage img; ImagePanel(String name) { this.setToolTipText(name); this.add(new JLabel(name)); try { img = ImageIO.read(new File(name)); this.setPreferredSize(new Dimension( img.getWidth(), img.getHeight())); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } @Override protected void paintComponent(Graphics g) { // super.paintComponent(g); g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null); } }}


