|
| 1 | +package org.example.graphicgame; |
| 2 | + |
| 3 | +import java.awt.*; |
| 4 | +import java.awt.event.MouseAdapter; |
| 5 | +import java.awt.event.MouseEvent; |
| 6 | +import java.util.OptionalDouble; |
| 7 | +import javax.swing.JFrame; |
| 8 | +import javax.swing.JPanel; |
| 9 | + |
| 10 | +public class DrawRectangleExample extends JFrame { |
| 11 | + private JPanel canvas; |
| 12 | + private Point startPoint; |
| 13 | + private Point endPoint; |
| 14 | + |
| 15 | + //private Rectangle[] objectArr; |
| 16 | + |
| 17 | + //private int a; |
| 18 | + |
| 19 | + public DrawRectangleExample() { |
| 20 | + setTitle("Draw Rectangle Example"); |
| 21 | + setSize(500, 500); |
| 22 | + setDefaultCloseOperation(EXIT_ON_CLOSE); |
| 23 | + //objectArr = new Rectangle[1000]; |
| 24 | + //a=0; |
| 25 | + |
| 26 | + canvas = new JPanel() { |
| 27 | + @Override |
| 28 | + protected void paintComponent(Graphics g) { |
| 29 | + super.paintComponent(g); |
| 30 | + this.setBackground(Color.BLACK); |
| 31 | + |
| 32 | + if (startPoint != null && endPoint != null) { |
| 33 | + int x = Math.min(startPoint.x, endPoint.x); |
| 34 | + int y = Math.min(startPoint.y, endPoint.y); |
| 35 | + int width = Math.abs(startPoint.x - endPoint.x); |
| 36 | + int height = Math.abs(startPoint.y - endPoint.y); |
| 37 | + g.setColor(Color.WHITE); |
| 38 | + g.drawRect(x, y, width, height); |
| 39 | + |
| 40 | + |
| 41 | + |
| 42 | + |
| 43 | + } |
| 44 | + |
| 45 | + |
| 46 | + } |
| 47 | + }; |
| 48 | + canvas.setBackground(Color.BLACK); |
| 49 | + canvas.addMouseMotionListener(new MouseAdapter() { |
| 50 | + @Override |
| 51 | + public void mouseDragged(MouseEvent e) { |
| 52 | + endPoint = e.getPoint(); |
| 53 | + canvas.repaint(); |
| 54 | + |
| 55 | + } |
| 56 | + }); |
| 57 | + canvas.addMouseListener(new MouseAdapter() { |
| 58 | + @Override |
| 59 | + public void mousePressed(MouseEvent e) { |
| 60 | + startPoint = e.getPoint(); |
| 61 | + |
| 62 | + |
| 63 | + |
| 64 | + } |
| 65 | + |
| 66 | + @Override |
| 67 | + public void mouseReleased(MouseEvent e) { |
| 68 | + endPoint = e.getPoint(); |
| 69 | + |
| 70 | + canvas.repaint(); |
| 71 | + |
| 72 | + } |
| 73 | + }); |
| 74 | + |
| 75 | + add(canvas); |
| 76 | + setVisible(true); |
| 77 | + } |
| 78 | + |
| 79 | + public static void main(String[] args) { |
| 80 | + new DrawRectangleExample(); |
| 81 | + } |
| 82 | +} |
| 83 | + |
0 commit comments