-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCircleButton.java
105 lines (86 loc) · 2.4 KB
/
CircleButton.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package bootathonfinal;
import javax.swing.JButton;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.geom.Point2D;
import java.awt.FontMetrics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class CircleButton extends JButton{
private boolean mouseOver = false;
private boolean mousePressed = false;
public CircleButton(String text){
super(text);
setOpaque(false);
setFocusPainted(false);
setBorderPainted(false);
MouseAdapter mouseListener = new MouseAdapter(){
@Override
public void mousePressed(MouseEvent me){
if(contains(me.getX(), me.getY())){
mousePressed = true;
repaint();
}
}
@Override
public void mouseReleased(MouseEvent me){
mousePressed = false;
repaint();
}
@Override
public void mouseExited(MouseEvent me){
mouseOver = false;
mousePressed = false;
repaint();
}
@Override
public void mouseMoved(MouseEvent me){
mouseOver = contains(me.getX(), me.getY());
repaint();
}
};
addMouseListener(mouseListener);
addMouseMotionListener(mouseListener);
}
private int getDiameter(){
int diameter = Math.min(getWidth(), getHeight());
return diameter;
}
@Override
public Dimension getPreferredSize(){
FontMetrics metrics = getGraphics().getFontMetrics(getFont());
int minDiameter = 10 + Math.max(metrics.stringWidth(getText()), metrics.getHeight());
return new Dimension(minDiameter, minDiameter);
}
@Override
public boolean contains(int x, int y){
int radius = getDiameter()/2;
return Point2D.distance(x, y, getWidth()/2, getHeight()/2) < radius;
}
@Override
public void paintComponent(Graphics g){
int diameter = getDiameter();
int radius = diameter/2;
if(mousePressed){
g.setColor(Color.LIGHT_GRAY);
}
else{
g.setColor(Color.WHITE);
}
g.fillOval(getWidth()/2 - radius, getHeight()/2 - radius, diameter, diameter);
if(mouseOver){
g.setColor(Color.gray);
}
else{
g.setColor(Color.white);
}
g.drawOval(getWidth()/2 - radius, getHeight()/2 - radius, diameter, diameter);
g.setColor(Color.decode("#5424BA"));
g.setFont(getFont());
FontMetrics metrics = g.getFontMetrics(getFont());
int stringWidth = metrics.stringWidth(getText());
int stringHeight = metrics.getHeight();
g.drawString(getText(), getWidth()/2 - stringWidth/2, getHeight()/2 + stringHeight/4);
}
}