understanding difficulties java swing

北城以北 提交于 2019-12-02 13:19:45

Painting and such happens event-driven. If a a piece of a component needs to be redrawn its paintComponent method is called.

This means you need a component that nows how to draw by for instance:

public class DrawShape {

    public final String text;
    public final Color color;
    public final Shape shape;

    public DrawShape(String text, Color color, Shape shape) {
        this.text = text;
        this.color = color;
        this.shape = shape;
    }
}

public class CanvasWithShapes extends JPanel {

    private List<DrawShape> shapes = new ArrayList<>();

    public void addShape(DrawShape shape) {
        shapes.add(shape);
    }

    @Override
    public void paintComponent(Graphics g) {
        final Graphics2D gg = (Graphics2D) g;
        // Java 8: shapes.stream().forEach((shape) -> gg.draw(shape));
        for (DrawShape drawShape : shapes) {
            gg.setColor(drawShape.color);
            gg.draw(drawShape.shape);
            Rectangle bounds = shape.getBounds();
            gg.drawString(shape.text, bounds.x+ 10, bounds.y + 20);
        }
    }
}

And then just add shapes to be redrawn a bit later.

Shape oval = ...;
c.add(oval);
c.repaint(50L); // A bit later 

More detailed

A Shape has many implementations of interest like rectangle and oval. Graphics2D can draw and fill a Shape. So in your case it would be ideal to add such a Shape. Maybe together with color and text. So I took your DrawShape class to hold these properties.

    Random generator = new Random();
    int x = generator.nextInt(100)+100;
    int y = generator.nextInt(100)+100;

    if (e.getActionCommand().equals("Draw RandomCircle")) {
        System.out.printf("x = %d y = %d\n", x, y);
        status.setText(String.format("rnd draw x:%d  y:%d ", x, y));
        int w = generator.nextInt(100) + 10;
        int h = w;
        Shape circle = new Ellipse2D.Double(x, y, w, h);
        addShape(new DrawShape(text, Color.BLACK, circle));
        int count = shapes.size(); 
        System.out.printf("objects in array: %d\n", count); 
    } else if (e.getActionCommand().equals("Draw RandomRectangle")) {
        System.out.printf("x = %d y = %d\n", x, y);

generator.nextInt(y)); int w = generator.nextInt(100) + 10; int h = generator.nextInt(100) + 10; Shape rect = Rectangle2D.Double(x, y, w, h) addShape(new DrawShape(text, Color.BLACK, rect)); }

Graphics2D gg = (Graphics2D) canvas.getGraphics();

Don't use the getGraphics() method to do painting. The painting is temporary. It will be lost if you resize the frame for example.

Instead you need to override the paintComponent() method of your panel.

If you want to paint multiple objects then you need to keep track of each object. Check out Custom Painting Approaches for the two common ways to do this:

  1. keep of List of Objects to paint and then iterate through the List each time the component is repainted.
  2. paint the Object directly to a BufferedImage and then just paint the BufferedImage.

The example paints Rectangles. Basically you need a method like the addRectangle(...) method to add a new object to paint. So every time you click your button you add the new random shape.

Presumably, your problem arises from the setText() invocation modifying the Graphics object in some unexpected way. It is rarely appropriate to use getGraphics() in your own code. Instead, paint with the Graphics that is given to you.

Your approach is anyway flawed. If you manage to draw on a GUI component only once, as you are trying to do, then whatever you have drawn will disappear when the component is next repainted. Repainting can happen for a wide variety of reasons, many of them unrelated to the program's own behavior.

What you need to do is store some kind of data that the component's paintComponent() method will rely upon to do your custom painting every time. It follows that you will need to override the paintComponent() method of the component on which you want the circles to be drawn. For example, you might create a class that records all the needed drawing details for one circle, and give RandomDrawer a List of those objects as a member variable. The action listener manipulates that list appropriately and schedules a repainting, and paintComponent() is overridden to perform the actual painting.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!