1092 java概論

題目說明

利用 AWT 或 Swing 視窗介面寫出一個有選單的視窗程式,選單有紅、藍、綠三個選項,選了之後會畫出現底色為某顏色的六邊形。
紅藍綠 三個 swing button

參考解法

修改自java simple painter

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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import javax.swing.JColorChooser;

public class hw2 extends Frame implements MouseListener, MouseMotionListener, ItemListener, ActionListener
{
static hw2 frm = new hw2();
static int x1, y1, x2, y2;
static int stroke = 1;
static Color color = Color.black;
static int lines = 0;
static Button line[];
Graphics2D g;
public static void main(String args[])
{
frm.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

frm.setTitle("simple painter");
frm.setSize(2000, 1000);
frm.setLayout(null);
set();
frm.addMouseListener(frm);
frm.addMouseMotionListener(frm);
frm.setVisible(true);
}

public static void set()
{
Label lb = new Label("color");
lb.setBounds(20, 30, 60, 20);
frm.add(lb);
line = new Button[3];
line[0] = new Button("red");
line[0].setBounds(80, 30, 50, 20);
line[0].addActionListener(frm);
line[1] = new Button("blue");
line[1].setBounds(140, 30, 50, 20);
line[1].addActionListener(frm);
line[2] = new Button("green");
line[2].setBounds(200, 30, 50, 20);
line[2].addActionListener(frm);
frm.add(line[0]);
frm.add(line[1]);
frm.add(line[2]);

}

public void mouseMoved(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}

public void mousePressed(MouseEvent e)
{
x1 = e.getX();
y1 = e.getY();

if (lines == 0)
{
g.setColor(Color.red);
}
if (lines == 1)
{
g.setColor(Color.blue);
}
if (lines == 2)
{
g.setColor(Color.green);
}

double r=Math.pow(Math.pow(x2-x1, 2)+Math.pow(y2-y1, 2),0.5)/2;

update(g);

int x[] = new int [6];
int y[] = new int [6];

Polygon a = new Polygon();

for(int i=0;i<6;++i)
{
x[i]=(int)(x1+ r*Math.cos(360/6 * (i+1) * Math.PI / 180));
y[i]=(int)(y1+ r*Math.sin(360/6 * (i+1) * Math.PI / 180));
a.addPoint(x[i], y[i]);
}
g.drawPolygon(a);
g.fillPolygon(x,y,6);
}

public void mouseDragged(MouseEvent e) {}
public void itemStateChanged(ItemEvent e) {}
public void clear(Graphics2D g) {}

public void choosered()
{
lines = 0;
}

public void chooseblue()
{
lines = 1;
}

public void choosegreen()
{
lines = 2;
}

public void actionPerformed(ActionEvent e)
{
Button b = (Button)e.getSource();
g = (Graphics2D)getGraphics();

if (b == line[0])
choosered();

if (b == line[1])
chooseblue();

if (b == line[2])
choosegreen();
}
}