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
|
package ui.gui.widgets;
import annotations.Assoc;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import javax.swing.*;
import java.awt.*;
import java.util.Collections;
import static com.google.zxing.EncodeHintType.ERROR_CORRECTION;
import static com.google.zxing.qrcode.decoder.ErrorCorrectionLevel.L;
/**
* A fixed-size panel displaying a QR code.
*/
public class QRPanel extends JPanel {
private final int size;
@Assoc(partOf = true, lowerBond = 0)
private BitMatrix data;
/**
* EFFECTS: Init with the specific rectangular size. Min size = max size = preferred size.
*/
public QRPanel(int size) {
super();
setSize(new Dimension(size, size));
setMaximumSize(new Dimension(size, size));
setMinimumSize(new Dimension(size, size));
setPreferredSize(new Dimension(size, size));
this.size = size;
}
/**
* EFFECTS: Draw the QR code. Leave white if no data is set.
* MODIFIES: this
*/
@Override
protected void paintComponent(Graphics graphics) {
super.paintComponent(graphics);
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, size, size);
if (data == null) {
return;
}
graphics.setColor(Color.BLACK);
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if (data.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
}
}
}
}
/**
* EFFECTS: Set data and repaint. Nullable.
* MODIFIES: this
*/
public void setData(String data) {
if (data == null) {
this.data = null;
invalidate();
return;
}
try {
this.data = new QRCodeWriter().encode(data, BarcodeFormat.QR_CODE, size, size,
Collections.singletonMap(ERROR_CORRECTION, L));
} catch (WriterException e) {
e.printStackTrace();
}
invalidate();
}
}
|