Untitled
unknown
java
2 years ago
3.0 kB
7
Indexable
import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.Graphics; import java.awt.Color; import java.security.SecureRandom; public class PolyShapes { public static void main(String... args) { JFrame application = new JFrame(); application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); application.setSize(250, 250); Shapes shapes = new Shapes(); application.add(shapes); shapes.createShapes(); application.setVisible(true); } } class Shapes extends JPanel { private MyShape shapes[] = new MyShape[10]; public void createShapes() { SecureRandom random = new SecureRandom(); int width = getWidth(); int height = getHeight(); System.out.printf("%d, %d",width, height); for (int i = 0; i < 10; i++) { int x1 = random.nextInt(width); int y1 = random.nextInt(height); int x2 = random.nextInt(width); int y2 = random.nextInt(height); float r = random.nextFloat(); float g = random.nextFloat(); float b = random.nextFloat(); Color randomColor = new Color(r, g, b); boolean filled = random.nextBoolean(); if (i%2 == 0) shapes[i] = new MyRect(x1, y1, x2, y2, randomColor, filled); else shapes[i] = new MyLine(x1, y1, x2, y2, randomColor); } } public void paintComponent(Graphics g) { super.paintComponent(g); for (int i = 0; i < 10; i++) { shapes[i].draw(g); } } } class MyRect extends MyShape { private boolean filled = false; @Override public void draw(Graphics g) { g.setColor(getColor()); g.fillRect(getX1(), getY1(), getX2(), getY2()); } public MyRect(int x1, int y1, int x2, int y2, Color color, boolean filled) { setX1(x1); setY1(y1); setX2(x2); setY2(y2); setColor(color); this.filled = filled; } } class MyLine extends MyShape { @Override public void draw(Graphics g) { g.setColor(getColor()); g.drawLine(getX1(), getY1(), getX2(), getY2()); } public MyLine(int x1, int y1, int x2, int y2, Color color) { setX1(x1); setY1(y1); setX2(x2); setY2(y2); setColor(color); } } abstract class MyShape extends JPanel { private int x1; private int y1; private int x2; private int y2; private Color color; public MyShape() { this.x1 = 0; this.y1 = 0; this.x2 = 0; this.y2 = 0; color = Color.BLACK; } public MyShape(int x1, int y1, int x2, int y2, Color color) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.color = color; } //public abstract void paintComponent(Graphics g); public abstract void draw(Graphics g); public void paintComponent(Graphics g) { super.paintComponent(g); draw(g); } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public int getX1() { return x1; } public void setX1(int x) { x1 = x; } public int getY1() { return y1; } public void setY1(int y) { y1 = y; } public int getX2() { return x2; } public void setX2(int x) { x2 = x; } public int getY2() { return y2; } public void setY2(int y) { y2 = y; } }
Editor is loading...
Leave a Comment