简体   繁体   中英

Swing - JPanel background color disappears

I'm trying to draw inside my JPanel but everytime I click, the background of my JPanel disappears. It draws a line where the mouse is. I think it has something to do with the 2D graphics Can someone help?

public Brush() {

addMouseListener(this);
    addMouseMotionListener(this);
    setBackground(Color.white);


 }
    @Override
    public void paintComponent(Graphics g) {

        Graphics2D g2;
       // super.paintComponent(g);

        g2 = (Graphics2D) g;

        g2.setColor(brushColor);
       g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setStroke(new BasicStroke(8, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL));
        //Ellipse2D.Double circle = new Ellipse2D.Double(p1.x,p1.y,20,20);

        g2.fillOval(p1.x,p1.y,20,20);

        }


        @Override
        public void mousePressed(MouseEvent e) {
            dragging = true;
            p1 = e.getPoint();
            repaint();
        }
        @Override
        public void mouseReleased(MouseEvent e) {
            dragging = false;
            p1 = e.getPoint();
            repaint();
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            if (dragging) {
                p1 = e.getPoint();
                repaint();
            }
        }

Always call the super.paintComponent(g) method inside of your override.

You're drawing wrong then. If you want to draw a bunch of ovals, then either

  • create a collection of them and draw them with a for loop in paintComponent, or
  • draw them in a BufferedImage which is then drawn in your paintComponent method.
  • If I want to draw a curve with the mouse, I usually create an ArrayList<Point> and draw lines between contiguous points, either in paintComponent or in a BufferedImage.

Again, your code is written to draw only one point (oval actually) within paintComponent. If coded correctly, this is all it will do.

I suggest, the easiest thing to do is:

  • Give you class an ArrayList<Point>
  • Add points when mouse is pressed and call repaint
  • In paintComponent , call the super method, and then use a for loop to iterate through the ArrayList.
  • Start the loop at the Point at item 1, not 0, and then draw a line between the previous Point and the current point.
  • To get fancier, you may wish to have an ArrayList<ArrayList<Point>> where you start a new ArrayList<Point> with each press of the mouse, finish it with each release and add it to the overall collection. This will allow several lines to be drawn.

Why not give this a go on your own first?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM