import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test01 {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,
300);
JPanel panel = new JPanel();
JButton button = new MyButton2("Button");
button.setFocusable(false);
button.setBorderPainted(false);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button is clicked");
}
});
panel.add(button);
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
class MyButton2 extends JButton {
private static final long serialVersionUID = 1965063150601339314L;
public MyButton2(String text) {
super(text);
setOpaque(false);
setContentAreaFilled(false); // 这一句非常重要, 否则父类还会绘制按钮的区域.
}
@Override
protected void paintComponent(Graphics g) {
int width = this.getWidth();
int height = this.getHeight();
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(Color.GRAY);
g2d.fillRoundRect(0,
0,
width,
height,
20,
20);
super.paintComponent(g); // 最后调用这个方法, 让父类绘制在按钮上绘制文字.
}
}
Blur一个按钮:
class MyButton2 extends JButton {
private static final long serialVersionUID = 1965063150601339314L;
public MyButton2(String text) {
super(text);
// setOpaque(false);
// setContentAreaFilled(false); // 这一句非常重要, 否则父类还会绘制按钮的区域.
}
@Override
protected void paintComponent(Graphics g) {
BufferedImage buf = new BufferedImage(getWidth(), getHeight(),
BufferedImage.TYPE_INT_RGB);
super.paintComponent(buf.getGraphics());
float[] my_kernel = { 0.10f, 0.10f, 0.10f, 0.10f, 0.20f, 0.10f, 0.10f,
0.10f, 0.10f };
ConvolveOp op = new ConvolveOp(new Kernel(3, 3, my_kernel));
Image img = op.filter(buf,
null);
g.drawImage(img,
0,
0,
null);
}
}
class ImageButton extends JButton {
private static final long serialVersionUID = 1965063150601339314L;
Image image = new ImageIcon("v4.png").getImage();
public ImageButton(String text) {
super(text);
setOpaque(false);
setFocusable(false);
setBorderPainted(false);
this.setPreferredSize(new Dimension(image.getWidth(this), image
.getHeight(this)));
}
@Override
protected void paintComponent(Graphics g) {
g.drawImage(image,
0,
0,
null);
}
}