swing各组件重绘外观

时间:2023-02-02 07:42:41

JPanle、JButton、JLabel等等组件,若想实现漂亮的外观,可以通过实现paintComponent(Graphics g)来完成。

示例:自定义JButton的鼠标经过与鼠标离开的效果。

一、新建NewButton类

package background;

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

import javax.swing.ImageIcon;
import javax.swing.JButton;

public class NewButton extends JButton {
	ImageIcon icon = null;
	
	public NewButton(){
		setBorder(null);//取消边框
		
		icon = new ImageIcon("button1.png");
		
		this.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseExited(MouseEvent e) {
				//鼠标离开
				icon = new ImageIcon("button1.png");
				repaint();//重绘图形,调用paintComponent
			}
			
			@Override
			public void mouseEntered(MouseEvent e) {
				//鼠标经过
				icon = new ImageIcon("button2.png");
				repaint();
			}
		});
	}
	
	public void paintComponent(Graphics g){
		int x=0,y=0;
		g.drawImage(icon.getImage(), x, y, 95, 32, this);
	}
}

二、主窗口JFrameDemo

package background;

import javax.swing.ImageIcon;
import javax.swing.JFrame;

public class JFrameDemo extends JFrame {
	public JFrameDemo(){
		super("Jpanel Background Demo");//窗口标题
		
		NewButton b2 = new NewButton();
		
		this.getContentPane().add(b2);//将button加入窗口
		
		this.setSize(95, 32);
		this.setLocationRelativeTo(null);//设置窗口居中
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.setVisible(true);
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new JPanelDemo();
	}

}

通过实现paintComponent可以实现各个组件的自定义外观。