2 import javax
.swing
.SwingUtilities
;
3 import javax
.swing
.JFrame
;
4 import javax
.swing
.JPanel
;
5 import javax
.swing
.BorderFactory
;
7 import java
.awt
.Dimension
;
8 import java
.awt
.Graphics
;
9 import java
.awt
.Graphics2D
;
10 import java
.awt
.GradientPaint
;
11 import java
.awt
.event
.MouseEvent
;
12 import java
.awt
.event
.MouseListener
;
13 import java
.awt
.event
.MouseAdapter
;
14 import java
.awt
.event
.MouseMotionListener
;
15 import java
.awt
.event
.MouseMotionAdapter
;
17 public class BasicGUI
{
19 public static void main(String
[] args
) {
21 SwingUtilities
.invokeLater(new Runnable() {
28 private static void createAndShowGUI() {
29 JFrame f
= new JFrame("Basic GUI #1 - Vertical string of shapes");
30 f
.setDefaultCloseOperation(JFrame
.EXIT_ON_CLOSE
);
38 class MyPanel
extends JPanel
{
40 final int START_X
= 10;
41 final int START_Y
= 10;
42 final int SHAPE_WIDTH
= 50;
43 final int SHAPE_HEIGHT
= 40;
44 final int SHAPE_SPACING
= 30;
45 final int SHAPE_COUNT
= 7;
48 setBorder(BorderFactory
.createLineBorder(Color
.black
));
51 public Dimension
getPreferredSize() {
52 return new Dimension(SHAPE_WIDTH
+ 2 * START_X
,
53 SHAPE_COUNT
* SHAPE_HEIGHT
+
54 (SHAPE_COUNT
- 1) * SHAPE_SPACING
+ 2 * START_Y
);
57 public void paintComponent(Graphics g
) {
58 final int SHAPE_MID_X
= START_X
+ SHAPE_WIDTH
/ 2;
61 super.paintComponent(g
);
63 Graphics2D g2d
= (Graphics2D
) g
;
64 Color color1
= getBackground();
65 Color color2
= color1
.darker();
69 // Draw vertical string of shapes
70 for(int i
= 0; i
< SHAPE_COUNT
- 1; i
++) {
71 gp
= new GradientPaint(START_X
, currY
, color1
,
72 START_X
, currY
+ SHAPE_HEIGHT
, color2
);
74 g2d
.fillRect(START_X
, currY
, SHAPE_WIDTH
, SHAPE_HEIGHT
);
76 g
.drawLine(SHAPE_MID_X
, currY
+ SHAPE_HEIGHT
,
77 SHAPE_MID_X
, currY
+ SHAPE_HEIGHT
+ SHAPE_SPACING
);
79 currY
+= SHAPE_HEIGHT
+ SHAPE_SPACING
;
83 gp
= new GradientPaint(START_X
, currY
, color1
,
84 START_X
, currY
+ SHAPE_HEIGHT
, color2
);
86 g2d
.fillRect(START_X
, currY
, SHAPE_WIDTH
, SHAPE_HEIGHT
);