Jullix993
Jullix993

Reputation: 105

Label gets added to JPanel without reason swing

I'm trying to make a simple application for painting. I have a main method that sets up a JFrame, and then adds a JPanel and a JLabel using flowlayout. The JLabel is for counting clicks.

The panel class implements a mouselistener and mousemotionlistener.

The problem is when I paint something or click on the panel, it adds the label to the JPanel aswell, and depending on where I click, it can add it twice to the panel, it's making me mad. I just can't understand why it's added to the JPanel.

Also, the JPanel is surrounded by a border, and when I click or paint something it adds a new vertical borderline somewhere on the panel, it's random every time.

Picture showing what I mean.

Code for the two classes:

public class mainepanel extends JPanel implements  MouseMotionListener, MouseListener{

Graphics globalGraphics;
int clickCount = 0;

public mainepanel(){
    setBorder(BorderFactory.createLineBorder(Color.black));
    setPreferredSize(new DimensionUIResource(200,200));
    addMouseMotionListener(this);
    addMouseListener(this);
    validate();
    setFocusable(true);
}

public void paintComponent(Graphics g){
    globalGraphics = g.create();
}

@Override
public void mouseDragged(MouseEvent e) {
    globalGraphics.fillOval(e.getX(), e.getY(), 10,10);
    repaint();
}

@Override
public void mouseClicked(MouseEvent e) {
    clickCount ++;
    maine.setLabel(clickCount);
    globalGraphics.fillOval(e.getX(), e.getY(), 10,10);
    repaint();
}

maine

public class maine extends JFrame{
static JLabel label;

public maine(){
    setSize(600,400);
    setDefaultCloseOperation(3);
    setResizable(false);

    label = new JLabel("Clicks:");
    setLayout(new FlowLayout());
    add(label);
    add(new mainepanel());
    setVisible(true);
}

public static void setLabel(int clicks){
    label.setText("Clicks: " + clicks);
}

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

Upvotes: 0

Views: 67

Answers (1)

copeg
copeg

Reputation: 8348

Perform all the drawing within paintComponent (and be sure to call super.paintComponent) - the MouseListener/MouseMotionListener should only need to change the data model (and if necessary call repaint so the UI reflects the change).

A simple example below with a single circle created with a Mouse click, and moved with a mouse dragged:

Point center = null;
...
@Override
public void mouseClicked(MouseEvent e){
    center = e.getPoint();
    repaint();
}
@Override
public void mouseDragged(MouseEvent e){
    center = e.getPoint();
    repaint();
}
@Override
protected void paintComponent(Graphics g){
    super.paintComponent(g);
    if ( center != null ){
        g.fillOval(center.getX(), center.getY(), 10, 10);
    }
}

Upvotes: 3

Related Questions