繼承JButton,做一個圓形的按鈕。
這是一個例子,根據這個,我們還可以描畫出很多特別的UI。
1
/**
2
* @author bzwm
3
*
4
*/
5
import java.awt.Color;
6
import java.awt.Cursor;
7
import java.awt.Dimension;
8
import java.awt.FlowLayout;
9
import java.awt.Graphics;
10
import java.awt.Shape;
11
import java.awt.event.MouseEvent;
12
import java.awt.geom.Ellipse2D;
13
import javax.swing.JButton;
14
import javax.swing.JFrame;
15
public class CircleButton extends JButton {
16
private Shape shape = null;// 用于保存按鈕的形狀,有助于偵聽單擊按鈕事件
17
18
public CircleButton(String label) {
19
super(label);
20
this.addMouseListener(new java.awt.event.MouseAdapter(){
21
/**
22
* {@inheritDoc}
23
*/
24
public void mouseEntered(MouseEvent e) {
25
((JButton)e.getSource()).setCursor(new Cursor(Cursor.HAND_CURSOR));
26
}
27
/**
28
* {@inheritDoc}
29
*/
30
public void mouseExited(MouseEvent e) {
31
((JButton)e.getSource()).setCursor(new Cursor(Cursor.MOVE_CURSOR));
32
}
33
});
34
Dimension size = getPreferredSize();// 獲取按鈕的最佳大小
35
// 調整按鈕的大小,使之變成一個方形
36
size.width = size.height = Math.max(size.width, size.height);
37
setPreferredSize(size);
38
// 使jbutton不畫背景,即不顯示方形背景,而允許我們畫一個圓的背景
39
setContentAreaFilled(false);
40
}
41
// 畫圖的按鈕的背景和標簽
42
protected void paintComponent(Graphics g) {
43
if (getModel().isArmed()) {
44
// getModel方法返回鼠標的模型ButtonModel
45
// 如果鼠標按下按鈕,則buttonModel的armed屬性為真
46
g.setColor(Color.LIGHT_GRAY);
47
} else {
48
// 其他事件用默認的背景色顯示按鈕
49
g.setColor(getBackground());
50
}
51
// fillOval方法畫一個矩形的內切橢圓,并且填充這個橢圓
52
// 當矩形為正方形時,畫出的橢圓便是圓
53
g.fillOval(0, 0, getSize().width - 1, getSize().height - 1);
54
// 調用父類的paintComponent畫按鈕的標簽和焦點所在的小矩形
55
super.paintComponents(g);
56
}
57
// 用簡單的弧充當按鈕的邊界
58
protected void paintBorder(Graphics g) {
59
g.setColor(getForeground());
60
// drawOval方法畫矩形的內切橢圓,但不填充,只畫出一個邊界
61
g.drawOval(0, 0, getSize().width - 1, getSize().height - 1);
62
}
63
// 判斷鼠標是否點在按鈕上
64
public boolean contains(int x, int y) {
65
// 如果按鈕邊框,位置發生改變,則產生一個新的形狀對象
66
if ((shape == null) || (!shape.getBounds().equals(getBounds()))) {
67
// 構造橢圓型對象
68
shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
69
}
70
// 判斷鼠標的x,y坐標是否落在按鈕形狀內
71
return shape.contains(x, y);
72
}
73
public static void main(String[] args) {
74
JButton button = new CircleButton("Click me");// 產生一個圓形按鈕
75
//button.setBackground(Color.green);// 設置背景色為綠色
76
// 產生一個框架顯示這個按鈕
77
JFrame frame = new JFrame("圖形按鈕");
78
frame.getContentPane().setBackground(Color.yellow);
79
frame.getContentPane().setLayout(new FlowLayout());
80
frame.getContentPane().add(button);
81
frame.setSize(200, 200);
82
frame.setVisible(true);
83
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
84
}
85
}

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

----2009年02月02日