create two icons with same size. one for noraml state, another for pressed state. import java.awt.*; import java.awt.geom.*; import javax.swing.*;class RoundButton extends JButton { Shape shape; public RoundButton() { super(); Dimension size = new Dimension(60,60); //60 is the width and height of // the button icon setPreferredSize(size); setContentAreaFilled(false); setIcon(new ImageIcon("006a.gif")); //button icon setPressedIcon(new ImageIcon("006b.gif")); //when pressed } protected void paintBorder(Graphics g) { //do nothing here, }
public boolean contains(int x, int y) { if (shape == null || !shape.getBounds().equals(getBounds())) { shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight()); } return shape.contains(x, y); } }
用JLabel,放圆行图片,然后在添加事件就行了。
Java Web Start 里面的 SwingSet2 App 里面有很多例子,不光是按钮,还有checkbox,radio什么的。有源代码,还可以直接看效果。
点击时模拟按下去的状态按好用JLable,因为JButton有它自己的响应点击的显示方式。
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;class RoundButton extends JButton {
Shape shape; public RoundButton() {
super();
Dimension size = new Dimension(60,60); //60 is the width and height of
// the button icon
setPreferredSize(size);
setContentAreaFilled(false);
setIcon(new ImageIcon("006a.gif")); //button icon
setPressedIcon(new ImageIcon("006b.gif")); //when pressed
} protected void paintBorder(Graphics g) {
//do nothing here,
}
public boolean contains(int x, int y) {
if (shape == null || !shape.getBounds().equals(getBounds())) {
shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
}
return shape.contains(x, y);
}
}
用paintComponent()方法也行吧