gregp
gregp

Reputation: 61

Trouble with repaint() GUI in Java

I have a problem with repaint my GUI. I want to paint some drawing like by brush on my central element, but when I'm dragging mouse all elements of GUI are printing on my central element. Do you have an idea how to fix it?

I can't post images, so there is link to pics: https://i.sstatic.net/M8OOd.jpg

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class PunsClient extends JFrame {

    //GUI
    private JButton polacz, rozlacz;
    private JPanel topPanel;
    private Painter painter;
    //Klient
    private String nazwaSerwera = "localhost";
    private Klient watekKlienta;
    private PunsClient instancjaKlienta;
    private Puns serwer;
    private ClientImpl klient;

    public PunsClient() {
        super("Klient");
        instancjaKlienta = this;
        setSize(700, 500); 
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        setLayout(new BorderLayout());
        topPanel = new JPanel(new FlowLayout()); 
        painter = new Painter();
        polacz = new JButton("Połącz");
        rozlacz = new JButton("Rozłącz");
        rozlacz.setEnabled(false);


        addWindowListener(new WindowAdapter() {

            public void windowClosing(WindowEvent e) {
                rozlacz.doClick();
                setVisible(false);
                System.exit(0);
            }
        });

        topPanel.add(new JLabel("Serwer RMI: "));
        topPanel.add(host);
        topPanel.add(polacz);
        topPanel.add(rozlacz);

        add(topPanel, BorderLayout.NORTH);
        add(painter, BorderLayout.CENTER);
        add(wiadomosc, BorderLayout.SOUTH);
        setVisible(true);
    }

    public static void main(String[] args) {
        new PunsClient();

    }
}


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Painter extends JPanel {

    int xvalue = -10, yvalue = -10;

   public Painter() {  
      setPreferredSize(new Dimension(400, 400));
      addMouseMotionListener(new MouseMotionAdapter() {

          public void mouseDragged( MouseEvent event ) {
              xvalue = event.getX();
              yvalue = event.getY();
              repaint();
              }
          });
      }

   public void paint ( Graphics g ) {
       g.fillOval( xvalue, yvalue, 10, 10 );
    }
   }

Upvotes: 0

Views: 67

Answers (1)

camickr
camickr

Reputation: 324098

Custom painting is done by overriding the paintComponent(..) method, not the paint() method.

And don't forget to invoke super.paintComponent() as the first statement in the paintComponent() method.

Read the section from the Swing tutorial on Custom Painting for more information and examples.

Also, if you want to do incremental painting then you should check out Custom Painting Approaches. The Draw On Image example is probably the approach you would use.

Upvotes: 1

Related Questions