public class Test {
public void run() {
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
MyButton btn = new MyButton("Hallo");
btn.addActionListener(e -> System.out.println("Hallo"));
frame.add(btn);
frame.setVisible(true);
}
class MyButton extends JButton {
private Shape shape;
public MyButton(String text) {
super(text);
setFocusable(false);
Dimension size = getPreferredSize();
size.width = size.height = Math.max(size.width, size.height);
setPreferredSize(size);
setContentAreaFilled(false);
}
@Override
protected void paintComponent(Graphics graphics) {
Graphics2D g = (Graphics2D) graphics;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(getModel().isArmed() || getModel().isRollover() ? Color.BLUE : getBackground());
g.fillOval(0, 0, getSize().width - 1, getSize().height - 1);
super.paintComponent(g);
}
@Override
protected void paintBorder(Graphics graphics) {
Graphics2D g = (Graphics2D) graphics;
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.BLACK);
g.drawOval(0, 0, getSize().width - 1, getSize().height - 1);
}
@Override
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);
}
}
public static void main(String[] args) {
new Test().run();
}
}