Sasha McCarn
Sasha McCarn

Reputation: 1

Painting on JPanels

I'm writing a program that will be just a simple shape maker, I'm supposed to my main panel, ShapeMakerPanel, along with 2 panels on that one, controlPanel(which holds buttons for choosing the shape and clearing it, etc) and drawingArea (where the shapes are actually drawn), but no matter what I do, I can't get the paint to show up on drawingArea. If I just use paintComponent and comment out add(drawingArea) then the drawing stuff works, but on the bottom layer, how can I paint on the drawingArea Jpanel. Also, when I do draw the shapes, I can only have one at a time, because every time I start a new one, the panel is wiped clean`

    super.paintComponent(g);
    g.setColor(penColor);
    if (p1 != null && p2 != null)
    {
        if (shapeChoice.getSelectedItem().equals("Line"))
        {
            Line line = new Line(p1.x, p1.y, p2.x, p2.y);
            line.draw(g);
        }
    }

I know its the super.paintComponent(g) messing me up, but without that, as I drag the mouse, it draws hundreds of lines.

If you were wondering about the Line class, we had to make a class for each shape we drew, the draw() method just uses the coordinates of the line and puts them into drawLine().

Upvotes: 0

Views: 687

Answers (2)

camickr
camickr

Reputation: 324108

Also, when I do draw the shapes, I can only have one at a time, because every time I start a new one, the panel is wiped clean`

See Custom Painting Approaches for a couple of ways to solve this.

Upvotes: 0

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

Don't override paintComponent() in ShapeMakerPanel; override it in drawingArea's class (if drawingArea is a plain JPanel, then create a new subclass of JPanel). In general you need to subclass the component on which you're going to paint.

Upvotes: 1

Related Questions