jframe 图片背景

It's not working very well. When the window opens, it is blank. I have to minimize it, then right click on the window in the Windows bar at the bottom of the screen, in the right-click menu select "Maximize"...when it maximizes, then the image appears...but it doesn't appear the first time around when the window opens. What could I be doing wrong?

Here's the code for my content pane:

public

 class

 BackgroundImagePanel extends

 JComponent {

 
	private

 Image backgroundImage = null

;
 
	/**
	 * Constructor
	 */

	public

 BackgroundImagePanel() {

		super

();
	}

 
	/**
	 * Returns the background image
	 * @return	Background image
	 */

	public

 Image getBackgroundImage() {

		return

 backgroundImage;
	}

 
	/**
	 * Sets the background image
	 * @param backgroundImage	Background image
	 */

	public

 void

 setBackgroundImage(Image backgroundImage) {

		this.backgroundImage = backgroundImage;
	}

	
	/**
	 * Overrides the painting to display a background image
	 */

	protected

 void

 paintComponent(Graphics g) {

		if

 (isOpaque()) {

			g.setColor(getBackground());
			g.fillRect(0, 0, getWidth(), getHeight());
		}

		if

 (backgroundImage != null

) {

			g.drawImage(backgroundImage,0,0,this

);
		}

	}

 
}



And here's the code for my main frame:

public

 class

 MainFrame extends

 JFrame {

 
	Image 		backImage;
 
	/**
	 * Constructor
	 */

	public

 MainFrame() {

		super

(""
);
		
		//handle window closing

		this.addWindowListener(new

 WindowAdapter() {

			public

 void

 windowClosing(WindowEvent e) {

			System.exit(0);
			}

		}
);
		this.setExtendedState(JFrame.MAXIMIZED_BOTH);
		
		//get background image

		backImage = Toolkit.getDefaultToolkit().getImage("wallpaper_adrift.jpg"
);
		BackgroundImagePanel contentPane = new

 BackgroundImagePanel();
		contentPane.setBackgroundImage(backImage);
		this.setContentPane(contentPane);
	}

	
	
	/**
	 * Main
	 * @param args	Command line arguments
	 */

	public

 static

 void

 main(String[] args) {

		MainFrame frame = new

 MainFrame();
		frame.setVisible(true

);
	}

}

你可能感兴趣的:(windows)