comparison examples/gui/swing/BLDComponent.java @ 1:5df24c91468d

Oh my what a mess.
author samer
date Fri, 05 Apr 2019 16:26:00 +0100
parents
children
comparison
equal deleted inserted replaced
0:bf79fb79ee13 1:5df24c91468d
1 import java.awt.*;
2 import java.awt.event.*;
3 import javax.swing.*;
4
5 /** A rectangle that has a fixed size. */
6 class BLDComponent extends JComponent {
7 private Color normalHue;
8 private final Dimension preferredSize;
9 private String name;
10 private boolean restrictMaximumSize;
11 private boolean printSize;
12
13 public BLDComponent(float alignmentX, float hue,
14 int shortSideSize,
15 boolean restrictSize,
16 boolean printSize,
17 String name) {
18 this.name = name;
19 this.restrictMaximumSize = restrictSize;
20 this.printSize = printSize;
21 setAlignmentX(alignmentX);
22 normalHue = Color.getHSBColor(hue, 0.4f, 0.85f);
23 preferredSize = new Dimension(shortSideSize*2, shortSideSize);
24
25 MouseListener l = new MouseAdapter() {
26 public void mousePressed(MouseEvent e) {
27 int width = getWidth();
28 float alignment = (float)(e.getX())
29 / (float)width;
30
31 // Round to the nearest 1/10th.
32 int tmp = Math.round(alignment * 10.0f);
33 alignment = (float)tmp / 10.0f;
34
35 setAlignmentX(alignment);
36 revalidate(); // this GUI needs relayout
37 repaint();
38 }
39 };
40 addMouseListener(l);
41 }
42
43 /**
44 * Our BLDComponents are completely opaque, so we override
45 * this method to return true. This lets the painting
46 * system know that it doesn't need to paint any covered
47 * part of the components underneath this component. The
48 * end result is possibly improved painting performance.
49 */
50 public boolean isOpaque() {
51 return true;
52 }
53
54 public void paint(Graphics g) {
55 int width = getWidth();
56 int height = getHeight();
57 float alignmentX = getAlignmentX();
58
59 g.setColor(normalHue);
60 g.fill3DRect(0, 0, width, height, true);
61
62 /* Draw a vertical white line at the alignment point.*/
63 // XXX: This code is probably not the best.
64 g.setColor(Color.white);
65 int x = (int)(alignmentX * (float)width) - 1;
66 g.drawLine(x, 0, x, height - 1);
67
68 /* Say what the alignment point is. */
69 g.setColor(Color.black);
70 g.drawString(Float.toString(alignmentX), 3, height - 3);
71
72 if (printSize) {
73 System.out.println("BLDComponent " + name + ": size is "
74 + width + "x" + height
75 + "; preferred size is "
76 + getPreferredSize().width + "x"
77 + getPreferredSize().height);
78 }
79 }
80
81 public Dimension getPreferredSize() {
82 return preferredSize;
83 }
84
85 public Dimension getMinimumSize() {
86 return preferredSize;
87 }
88
89 public Dimension getMaximumSize() {
90 if (restrictMaximumSize) {
91 return preferredSize;
92 } else {
93 return super.getMaximumSize();
94 }
95 }
96
97 public void setSizeRestriction(boolean restrictSize) {
98 restrictMaximumSize = restrictSize;
99 }
100
101 }