-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPaintApplication.java
More file actions
456 lines (388 loc) · 17.4 KB
/
PaintApplication.java
File metadata and controls
456 lines (388 loc) · 17.4 KB
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.io.File;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
public class PaintApplication extends JFrame {
// Drawing components
private DrawPanel drawPanel;
private Color currentColor = Color.BLACK;
private int brushSize = 5;
private String currentTool = "Pencil";
// UI Components
private JButton pencilBtn, lineBtn, rectangleBtn, ovalBtn, eraserBtn, textBtn;
private JButton colorBtn, clearBtn, saveBtn, openBtn;
private JSlider sizeSlider;
private JLabel sizeLabel, colorLabel;
private JComboBox<String> fontComboBox;
private JSpinner fontSizeSpinner;
// Tools constants
private final String[] FONTS = {"Arial", "Times New Roman", "Courier New", "Verdana", "Comic Sans MS"};
public PaintApplication() {
setTitle("Java Paint Application");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(1000, 700);
setLocationRelativeTo(null);
initializeComponents();
layoutComponents();
addEventListeners();
setVisible(true);
}
private void initializeComponents() {
// Drawing panel
drawPanel = new DrawPanel();
drawPanel.setBackground(Color.WHITE);
// Tool buttons
pencilBtn = createToolButton("Pencil", "Pencil");
lineBtn = createToolButton("Line", "Line");
rectangleBtn = createToolButton("Rect", "Rectangle");
ovalBtn = createToolButton("Oval", "Oval");
eraserBtn = createToolButton("Eraser", "Eraser");
textBtn = createToolButton("Text", "Text");
// Control buttons
colorBtn = new JButton("Color");
colorBtn.setBackground(currentColor);
colorBtn.setForeground(Color.WHITE);
clearBtn = new JButton("Clear");
saveBtn = new JButton("Save");
openBtn = new JButton("Open");
// Size slider
sizeSlider = new JSlider(1, 50, brushSize);
sizeLabel = new JLabel("Size: " + brushSize);
// Color preview
colorLabel = new JLabel("■");
colorLabel.setForeground(currentColor);
colorLabel.setFont(new Font("Arial", Font.BOLD, 24));
// Text tools
fontComboBox = new JComboBox<>(FONTS);
fontSizeSpinner = new JSpinner(new SpinnerNumberModel(20, 10, 72, 1));
// Set initial active tool
pencilBtn.setBackground(Color.LIGHT_GRAY);
}
private JButton createToolButton(String text, String tooltip) {
JButton button = new JButton(text);
button.setToolTipText(tooltip);
button.setFont(new Font("Arial", Font.PLAIN, 12));
return button;
}
private void layoutComponents() {
setLayout(new BorderLayout());
// Top panel - tools
JPanel toolPanel = new JPanel(new FlowLayout());
toolPanel.setBorder(BorderFactory.createTitledBorder("Tools"));
toolPanel.add(pencilBtn);
toolPanel.add(lineBtn);
toolPanel.add(rectangleBtn);
toolPanel.add(ovalBtn);
toolPanel.add(eraserBtn);
toolPanel.add(textBtn);
// Control panel
JPanel controlPanel = new JPanel(new FlowLayout());
controlPanel.setBorder(BorderFactory.createTitledBorder("Controls"));
controlPanel.add(colorBtn);
controlPanel.add(colorLabel);
controlPanel.add(sizeLabel);
controlPanel.add(sizeSlider);
controlPanel.add(clearBtn);
controlPanel.add(saveBtn);
controlPanel.add(openBtn);
// Text tools panel
JPanel textPanel = new JPanel(new FlowLayout());
textPanel.setBorder(BorderFactory.createTitledBorder("Text Tools"));
textPanel.add(new JLabel("Font:"));
textPanel.add(fontComboBox);
textPanel.add(new JLabel("Size:"));
textPanel.add(fontSizeSpinner);
// Combine all control panels
JPanel topPanel = new JPanel(new GridLayout(3, 1));
topPanel.add(toolPanel);
topPanel.add(controlPanel);
topPanel.add(textPanel);
// Main layout
add(topPanel, BorderLayout.NORTH);
add(new JScrollPane(drawPanel), BorderLayout.CENTER);
// Status bar
JLabel statusLabel = new JLabel(" Ready - Use mouse to draw");
statusLabel.setBorder(BorderFactory.createLoweredBevelBorder());
add(statusLabel, BorderLayout.SOUTH);
}
private void addEventListeners() {
// Tool selection
pencilBtn.addActionListener(e -> setActiveTool("Pencil"));
lineBtn.addActionListener(e -> setActiveTool("Line"));
rectangleBtn.addActionListener(e -> setActiveTool("Rectangle"));
ovalBtn.addActionListener(e -> setActiveTool("Oval"));
eraserBtn.addActionListener(e -> setActiveTool("Eraser"));
textBtn.addActionListener(e -> setActiveTool("Text"));
// Color selection
colorBtn.addActionListener(e -> chooseColor());
// Size slider
sizeSlider.addChangeListener(e -> {
brushSize = sizeSlider.getValue();
sizeLabel.setText("Size: " + brushSize);
drawPanel.setBrushSize(brushSize);
});
// Actions
clearBtn.addActionListener(e -> drawPanel.clearCanvas());
saveBtn.addActionListener(e -> saveDrawing());
openBtn.addActionListener(e -> openImage());
}
private void setActiveTool(String tool) {
currentTool = tool;
// Reset all button backgrounds
Component[] tools = {pencilBtn, lineBtn, rectangleBtn, ovalBtn, eraserBtn, textBtn};
for (Component comp : tools) {
comp.setBackground(null);
}
// Set active button background
switch (tool) {
case "Pencil": pencilBtn.setBackground(Color.LIGHT_GRAY); break;
case "Line": lineBtn.setBackground(Color.LIGHT_GRAY); break;
case "Rectangle": rectangleBtn.setBackground(Color.LIGHT_GRAY); break;
case "Oval": ovalBtn.setBackground(Color.LIGHT_GRAY); break;
case "Eraser": eraserBtn.setBackground(Color.LIGHT_GRAY); break;
case "Text": textBtn.setBackground(Color.LIGHT_GRAY); break;
}
drawPanel.setCurrentTool(tool);
}
private void chooseColor() {
Color newColor = JColorChooser.showDialog(this, "Choose Color", currentColor);
if (newColor != null) {
currentColor = newColor;
colorBtn.setBackground(currentColor);
colorBtn.setForeground(getContrastColor(currentColor));
colorLabel.setForeground(currentColor);
drawPanel.setCurrentColor(currentColor);
}
}
private Color getContrastColor(Color color) {
// Calculate contrast color for text
double luminance = (0.299 * color.getRed() + 0.587 * color.getGreen() + 0.114 * color.getBlue()) / 255;
return luminance > 0.5 ? Color.BLACK : Color.WHITE;
}
private void saveDrawing() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter("PNG Images", "png"));
int result = fileChooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
if (!file.getName().toLowerCase().endsWith(".png")) {
file = new File(file.getAbsolutePath() + ".png");
}
try {
// Create image from drawing panel
java.awt.image.BufferedImage image = new java.awt.image.BufferedImage(
drawPanel.getWidth(), drawPanel.getHeight(), java.awt.image.BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
drawPanel.printAll(g2d);
g2d.dispose();
ImageIO.write(image, "PNG", file);
JOptionPane.showMessageDialog(this, "Drawing saved successfully!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error saving file: " + ex.getMessage(),
"Save Error", JOptionPane.ERROR_MESSAGE);
}
}
}
private void openImage() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileFilter(new FileNameExtensionFilter(
"Image Files", "jpg", "jpeg", "png", "gif", "bmp"));
int result = fileChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
try {
File file = fileChooser.getSelectedFile();
java.awt.image.BufferedImage image = ImageIO.read(file);
drawPanel.setBackgroundImage(image);
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error opening file: " + ex.getMessage(),
"Open Error", JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String[] args) {
// Fixed UIManager call
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(() -> new PaintApplication());
}
// Inner class for drawing panel
class DrawPanel extends JPanel {
private ArrayList<Shape> shapes = new ArrayList<>();
private ArrayList<Color> shapeColors = new ArrayList<>();
private ArrayList<Integer> shapeSizes = new ArrayList<>();
private ArrayList<String> shapeTypes = new ArrayList<>();
private Point startPoint, endPoint;
private java.awt.image.BufferedImage backgroundImage;
public DrawPanel() {
setPreferredSize(new Dimension(800, 600));
setupMouseListeners();
}
private void setupMouseListeners() {
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
startPoint = e.getPoint();
endPoint = e.getPoint();
if (currentTool.equals("Text")) {
String text = JOptionPane.showInputDialog(PaintApplication.this, "Enter text:");
if (text != null && !text.trim().isEmpty()) {
addTextShape(text, e.getPoint());
}
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (startPoint != null && endPoint != null && !currentTool.equals("Pencil") && !currentTool.equals("Eraser") && !currentTool.equals("Text")) {
createShape();
}
startPoint = null;
endPoint = null;
repaint();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
endPoint = e.getPoint();
if (currentTool.equals("Pencil") || currentTool.equals("Eraser")) {
addFreehandPoint(e.getPoint());
}
repaint();
}
});
}
private void createShape() {
if (startPoint == null || endPoint == null) return;
Shape shape = null;
switch (currentTool) {
case "Line":
shape = new Line2D.Double(startPoint, endPoint);
break;
case "Rectangle":
shape = new Rectangle2D.Double(
Math.min(startPoint.x, endPoint.x),
Math.min(startPoint.y, endPoint.y),
Math.abs(endPoint.x - startPoint.x),
Math.abs(endPoint.y - startPoint.y)
);
break;
case "Oval":
shape = new Ellipse2D.Double(
Math.min(startPoint.x, endPoint.x),
Math.min(startPoint.y, endPoint.y),
Math.abs(endPoint.x - startPoint.x),
Math.abs(endPoint.y - startPoint.y)
);
break;
}
if (shape != null) {
shapes.add(shape);
shapeColors.add(currentTool.equals("Eraser") ? getBackground() : currentColor);
shapeSizes.add(brushSize);
shapeTypes.add(currentTool);
}
}
private void addFreehandPoint(Point point) {
if (startPoint != null) {
Shape line = new Line2D.Double(startPoint, point);
shapes.add(line);
shapeColors.add(currentTool.equals("Eraser") ? getBackground() : currentColor);
shapeSizes.add(brushSize);
shapeTypes.add(currentTool);
startPoint = point;
}
}
private void addTextShape(String text, Point position) {
// Create a custom shape for text
Shape textShape = new Rectangle2D.Double(position.x, position.y, 10, 10); // Placeholder
shapes.add(textShape);
shapeColors.add(currentColor);
shapeSizes.add((Integer) fontSizeSpinner.getValue());
shapeTypes.add("Text:" + text + ":" + fontComboBox.getSelectedItem() + ":" + position.x + ":" + position.y);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
// Draw background image if exists
if (backgroundImage != null) {
g2d.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), this);
}
// Enable anti-aliasing for smoother graphics
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// Draw all shapes
for (int i = 0; i < shapes.size(); i++) {
g2d.setColor(shapeColors.get(i));
g2d.setStroke(new BasicStroke(shapeSizes.get(i)));
String type = shapeTypes.get(i);
if (type.startsWith("Text:")) {
// Handle text rendering
String[] parts = type.split(":");
if (parts.length >= 5) {
String text = parts[1];
String fontName = parts[2];
int x = Integer.parseInt(parts[3]);
int y = Integer.parseInt(parts[4]);
g2d.setFont(new Font(fontName, Font.PLAIN, shapeSizes.get(i)));
g2d.drawString(text, x, y);
}
} else {
// Draw geometric shapes
g2d.draw(shapes.get(i));
}
}
// Draw preview of current shape being drawn
if (startPoint != null && endPoint != null && !currentTool.equals("Pencil") && !currentTool.equals("Eraser") && !currentTool.equals("Text")) {
g2d.setColor(currentColor);
g2d.setStroke(new BasicStroke(brushSize));
switch (currentTool) {
case "Line":
g2d.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y);
break;
case "Rectangle":
int x = Math.min(startPoint.x, endPoint.x);
int y = Math.min(startPoint.y, endPoint.y);
int width = Math.abs(endPoint.x - startPoint.x);
int height = Math.abs(endPoint.y - startPoint.y);
g2d.drawRect(x, y, width, height);
break;
case "Oval":
x = Math.min(startPoint.x, endPoint.x);
y = Math.min(startPoint.y, endPoint.y);
width = Math.abs(endPoint.x - startPoint.x);
height = Math.abs(endPoint.y - startPoint.y);
g2d.drawOval(x, y, width, height);
break;
}
}
}
public void clearCanvas() {
shapes.clear();
shapeColors.clear();
shapeSizes.clear();
shapeTypes.clear();
backgroundImage = null;
repaint();
}
public void setCurrentTool(String tool) {
currentTool = tool;
}
public void setCurrentColor(Color color) {
currentColor = color;
}
public void setBrushSize(int size) {
brushSize = size;
}
public void setBackgroundImage(java.awt.image.BufferedImage image) {
this.backgroundImage = image;
repaint();
}
}
}