package com.ueky;
|
|
import java.awt.Color;
|
import java.awt.FontMetrics;
|
import java.awt.Graphics;
|
|
import javax.swing.BorderFactory;
|
import javax.swing.Icon;
|
import javax.swing.JButton;
|
|
public class MyJButton extends JButton {
|
private Icon icon;
|
|
public MyJButton(Icon icon) {
|
super();
|
this.icon = icon;
|
setBorder(BorderFactory.createEmptyBorder()); // ÒÆ³ýĬÈϱ߿ò
|
setContentAreaFilled(false); // ²»Ìî³ä°´Å¥±³¾°
|
}
|
|
public MyJButton(String text) {
|
super();
|
this.setText(text);
|
}
|
|
protected void paintComponent(Graphics g) {
|
System.out.println("########");
|
// »æÖư´Å¥±³¾°£¨Èç¹ûÐèÒª£©
|
//super.paintComponent(g);
|
|
// »æÖÆÍ¼±ê
|
if (icon != null) {
|
int iconWidth = icon.getIconWidth();
|
int iconHeight = icon.getIconHeight();
|
int x = (getWidth() - iconWidth) / 2;
|
int y = (getHeight() - iconHeight) / 2;
|
icon.paintIcon(this, g, x, y + getFont().getSize() -50); // 5ÊÇÎÄ×ÖºÍͼ±êÖ®¼äµÄ¶îÍâ¼ä¸ô
|
}
|
|
// »æÖÆÎı¾
|
if (getText() != null) {
|
FontMetrics metrics = g.getFontMetrics();
|
int textWidth = metrics.stringWidth(getText());
|
int textHeight = metrics.getHeight();
|
int x = (getWidth() - textWidth) / 2;
|
int y = (getHeight() + icon.getIconHeight()) / 2 + metrics.getDescent();
|
g.drawString(getText(), x, y);
|
}
|
|
//ÉèÖð´Å¥µÄ±³¾°É«£¬ÒÔ±ã¸üÃ÷ÏԵؿ´µ½±ß¿òµÄ±ä»¯
|
setBackground(Color.yellow);
|
//È¥³ý±ß¿ò
|
//setBorder(null);
|
|
}
|
}
|