Reputation: 707
I am trying to make something similar to Paint and I've run into a bit of a snag. Basically you paint in a JPanel that calls paintComponent(). However, when the program is run, an unwanted dot appears in the upper left corner. I think it is because paintComponent() is called at the start of the program. Is there any way to disable this? The code is listed below (I removed the imports) and thanks for reading. Here is the paintBoard class:
public class PaintBoard extends JPanel implements MouseListener
{
Image img;
//PaintBoard panel;
int circleX = 25;
int circleY = 25;
int x;
int y;
public PaintBoard()
{
this.addMouseListener(this);
}
public void paintComponent(Graphics g)
{
g.setColor(Color.RED);
g.fillOval(x, y, circleX, circleY);
}
public void mouseClicked(MouseEvent arg0)
{
}
public void mouseEntered(MouseEvent arg0)
{
}
public void mouseExited(MouseEvent arg0)
{
}
public void mousePressed(MouseEvent arg0)
{
x = arg0.getX();
y = arg0.getY();;
repaint();
}
public void mouseReleased(MouseEvent arg0)
{
}
}
And here is the main class:
public class Main
{
JFrame mainFrame = new JFrame("Painting test");
PaintBoard board = new PaintBoard();
public Main() throws IOException
{
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setSize(1750, 1000);
mainFrame.setLayout(new GridLayout(2, 2));
mainFrame.add(board);
//mainFrame.pack();
mainFrame.setVisible(true);
}
public static void main(String[] args) throws IOException
{
new Main();
}
}
Upvotes: 0
Views: 88
Reputation: 347194
The problem is that the x/y coordinates have been initialised to 0/0, so you're paint method is doing just what you asked it to do.
It would better to set the x/y coordinates to some value you can recognise and simply not paint the oval, something like -1/-1 for example
int x = -1;
int y = -1;
public void paintComponent(Graphics g)
{
if (x >= 0 && y >= 0) {
g.setColor(Color.RED);
g.fillOval(x, y, circleX, circleY);
}
}
Just note that Markus's solution is a better solution, this just solves the problem
Upvotes: 1
Reputation: 3497
That is a bit wrong. you want to have a backbuffer which is a bufferedimage, which you draw to when mouse is down and moved or when mouse button is lifted. Every time paintComponent is called you want to copy this backbuffer to the component with graphics.draw, or something like that.
Upvotes: 2