There is a frame with a button and a JPanel panel. On JPanel draw shapes. This is the frame:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { ((Canvas)canvas).shape = new Rect(); }
This is the Canvas code:
import java.awt.Color; import java.awt.Graphics; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; public class Canvas extends javax.swing.JPanel { public Shape shape = null; Queue myQueue = new Queue(); public Canvas(){ super(); } @Override public void paint(Graphics g){ g.setColor(Color.white); g.fillRect(0, 0, getWidth(), getHeight()); if (shape != null) { shape.color = new Color((int)(Math.random() * 256), (int)(Math.random() * 256), (int)(Math.random() * 256)); myQueue.addShape(shape); System.out.println("shape " + shape); for (int i = myQueue.getSize; i>-1; --i){ shape = myQueue.getShape(i); shape.paint(g); } } try { shape = shape.getClass().newInstance(); } catch (InstantiationException | IllegalAccessException ex) { Logger.getLogger(Canvas.class.getName()).log(Level.SEVERE, null, ex); } repaint(); } }
Shape:
import java.awt.Color; import java.awt.Graphics; import java.awt.MouseInfo; import java.awt.Point; public abstract class Shape { public int x1, y1, x2, y2; public Color color; public String name = "Shape"; public void paint(Graphics g){ g.setColor(color); draw(g); } public abstract void draw(Graphics g); /** * * @param evt */ public void MouseClicked(java.awt.event.MouseEvent evt) { } }
Rect:
import java.awt.Graphics; import java.awt.MouseInfo; import java.awt.Point; import java.awt.event.MouseEvent; import javax.swing.JToggleButton; public class Rect extends Shape { @Override public void draw(Graphics g){ g.fillRect(100, 100, 100, 100); } }
Queue:
import java.util.ArrayList; public class Queue { public ArrayList<Shape> shapes = new ArrayList<>(); public Shape nowshapes = null; int getSize; public void addShape(Shape newshapes){ shapes.add(newshapes); nowshapes = newshapes; } public Shape getShape(int i){ return shapes.get(i); } public void getSize(){ getSize = shapes.size(); } }
Actually, what is the problem: the shape class is not overridden. The figure is entered in the queue only once when you click on the button for the first time. Those. Further pressing the button leads to nothing. How to fix?
Rect
and assigns it to the field. Then, whenpaint()
happens, the object from the field gets a random color and is put intomyQueue
. Then the first object inmyQueue
is drawn (sincegetSize
infor
is an uninitialized class field of 0), a newRect
is created and added tocanvas.shape
, and the process is repeated endlessly with a call torepaint()
. What is all this for? - zRrr