Java重新绘制JButton
正常状态:
获得焦点状态:
被按下状态:
被释放状态:
实现代码:
[java]
package com.han;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RadialGradientPaint;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.font.LineMetrics;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.UnsupportedLookAndFeelException;
@SuppressWarnings("serial")
public class JButton_Bg extends JFrame {
public JButton_Bg() {
for (LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
if (laf.getName().equals("Nimbus")) {
try {
UIManager.setLookAndFeel(laf.getClassName());
} catch (ClassNotFoundException | InstantiationException
| IllegalAccessException
| UnsupportedLookAndFeelException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// TODO Auto-generated constructor stub
Container c = getContentPane();
c.setLayout(new FlowLayout());
final JButton button = new MyButton("button 2");
c.add(button);
JButton button2 = new JButton("button 2");
c.add(button2);
button2.setBackground(Color.blue);
JButton button3 = new MyButton2("Cancel");
c.add(button3);
// 完全重绘的Button,其Text的HTML设置特性消失
// JButton button4 = new
// MyButton3("<html><font size=12>Sub</font></html>");
JButton button4 = new MyButton3("Sub");
// button4.setFont(new Font("Serif", Font.PLAIN, 14));
c.add(button4);
}
private class MyButton extends JButton {
private String text;
private String state = "normal";
// private String state = "focused";
// private String state = "pressed";
// private String state = "released";
// 无参构造继承时自动调用,而有参构造继承时则需手动重写
MyButton(String text) {
// super("<html><font size=5>" + text + "</font></html>");
super(text);
this.text = text;
// 下 面的代码块若是放到下面的paintComponent()方法里则Swing界面初始化时,
// 布局管理器还是采用的是系统默认的PreferredSize。因为构造函数要优先于
// paintComponent()方法执行。
Dimension preferredSize = getPreferredSize();
Dimension preferredSizeNew = new Dimension(preferredSize.width,
preferredSize.width);
setPreferredSize(preferredSizeNew);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int width = this.getPreferredS
补充:软件开发 , Java ,