Ok, so I am trying to make a paint project and I am successful so far. I have a "canvas" to draw on and I have a toolbar menu with the color choices. I have made a button and method with drawLine() which takes my current coordinates via the mouse motion listener and my end coordinates, basically drawing the line wherever and however I like on the canvas. Now I want to add a button that when clicked, will draw an oval/circle on my canvas. Here come the problems tho.
First problem - I can get it to draw the oval on my mouse coordinates, but I cannot drag in order to change its size before I release the mouse button and actually paint it (just like you would in Microsoft paint).
Second problem - When I have selected my "Line" button which invokes my draw line method, I can draw lines and its fine, but then when I click the "Oval" button, it draws the Oval but also puts a line when I click the mouse (I am assuming that I need to disable the mouse motion listener on the Line when I select the Oval.) The Opposite is also true, If I have selected the "Oval" button and drawn ovals before, then click the "Line" button, it will draw a line but also put an oval each time I click to start drawing a line.
This is how my simple program looks like: Image
Here is part of the code concerning the drawLine, drawOval and my coordinate gathering methods, since everything else is working as intended:
// Image in which we're drawing.
private Image image;
// Graphics2D object which we used to draw on.
private Graphics2D g2;
// Mouse coordinates
private int currentX, currentY, oldX, oldY;
public DrawArea(){
setDoubleBuffered(false);
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
//save coordinates x,y when mouse is pressed.
oldX=e.getX();
oldY=e.getY();
}});
}
protected void paintComponent(Graphics g){
if (image==null){
//image to draw null ==> we create
image = createImage(getSize().width, getSize().height);
g2 = (Graphics2D) image.getGraphics();
//enable antialiasing.
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
//clear draw area
clear();
}
g.drawImage(image, 0, 0, null);
}
public void clear(){
g2.setPaint(Color.white);
//draw white on entire draw are to clear it.
g2.fillRect(0, 0, getSize().width, getSize().height);
g2.setPaint(Color.black);
repaint();
}
public void Line(){
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
//coordinates x,y when dragging mouse.
currentX=e.getX();
currentY=e.getY();
if (g2 != null){
g2.drawLine(oldX, oldY, currentX, currentY);
repaint();
oldX = currentX;
oldY = currentY;
}
}
});
}
public void Oval(){
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
currentX=e.getX();
currentY=e.getY();
if (g2 != null){
g2.drawOval(oldX, oldY, currentX, currentY);
repaint();
}
}
});
}
Aucun commentaire:
Enregistrer un commentaire