重写paintComponent方法以实现jPanel加背景


package Mange;

import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

/**
 *
 * @author FF
 */
public class RePanel extends JPanel{
    protected void paintComponent(Graphics g){//重写paintComponent方法以实现jPanel加背景
        super.paintComponent(g);
        ImageIcon image=new ImageIcon(getClass().getResource("/Images/background.jpg"));        //获取图像
        image.setImage(image.getImage().getScaledInstance(this.getWidth(),this.getHeight(),Image.SCALE_FAST)); //调整图像的分辨率以适应容器
        image.paintIcon(this, g,0, 0);
    }
}
分享:

4 条评论

JamesY0ung

你好,我用你的方法实现了更改背景,我现在想用点击按钮更换panel背景,大概是要在按钮的函数里面重写panel的方法,百度了很久,根本查不到,想问下有经验的人能够写出来吗?

回复
骑驴过街

N年不用java写图形界面,但想了想,在点击事件中给上边图形重绘的方法重新来一遍应该可行。代码如下:

package com.yimik.test.swing;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class BackgroundTest extends JFrame{
	private static final long serialVersionUID = 1L;
	private JButton b;
	private JPanel p ;
	
	public BackgroundTest() {
		p = new MyPanel();
		p.setBounds(0, 0, 500,200);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setSize(500, 500);
		this.setVisible(true);
		this.setLayout(null);
		this.add(p);
		b = new JButton("点击换背景");
		b.setBounds(0, 300, 100, 30);
		this.add(b);
		b.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				super.mouseClicked(e);
				ImageIcon image=new ImageIcon(getClass().getResource("/imgs/img2.jpg"));
		        image.setImage(image.getImage().getScaledInstance(p.getWidth(),p.getHeight(),Image.SCALE_FAST));
		        image.paintIcon(p, p.getGraphics(),0, 0);
			}
		});
	}
	
	public static void main(String[] args) {
		new BackgroundTest();
	}
}
class MyPanel extends JPanel{
	private static final long serialVersionUID = 1L;

	@Override
	protected void paintComponent(Graphics g){//重写paintComponent方法以实现jPanel加背景
        super.paintComponent(g);
        ImageIcon image=new ImageIcon(getClass().getResource("/imgs/img1.jpg"));        //获取图像
        image.setImage(image.getImage().getScaledInstance(this.getWidth(),this.getHeight(),Image.SCALE_FAST)); //调整图像的分辨率以适应容器
        image.paintIcon(this, g,0, 0);
    }
}
回复
JamesY0ung

首先谢谢楼主啦,辛苦了,在看你代码之前我想到了这个方法,但是估计是多个面板的缘故,背景换成功了,然后其他面板的组件例如按钮那些都看不见了,要用鼠标滑过才出现,貌似是因为重绘后其他组件要重新初始化一次,我自己先想想,实在不行再看你的代码,好吗?

回复

发表评论

电子邮件地址不会被公开。 必填项已用*标注

😉😐😡😈🙂😯🙁🙄😛😳😮:mrgreen:😆💡😀👿😥😎😕

验证码 *