Live drawn shape representation - best way to clear last live image?
The title may not explain clearly what I'm trying to express.
When you use an image editor such as PS, PSP, Inkscape or GIMP, if you eg. try to make a selection using the rectangular selection tool, there is a 'live' rectangle displayed as you drag the mouse around with the button depressed.
This is the effect I wish to obtain.
I simply wondered, is the most efficient way of achieving this effect to draw over your last mouseDragged rectangle with the background colour of your (eg.) BufferedImage, and then draw a new rectangle on your Image in a non-background colour? Or would it be faster to utilise a separate Image object that you completely clear and draw onto each time the mouse is dragged, then render this image onto your 'actual' image?
I hope I have explained myself sufficiently clearly; please let me know if this is not the case.
# 3
Or maybe you just do override the paintComponent() method of the label displying the image with somethink like this:
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class DrawSquare extends JPanel
{
Point startPoint = null;
Point endPoint = null;
public DrawSquare()
{
setPreferredSize(new Dimension(500,500));
MyMouseListener ml = new MyMouseListener();
addMouseListener(ml);
addMouseMotionListener(ml);
setBackground(Color.white);
}
public void paintComponent(Graphics g)
{
// automatically called when repaint
super.paintComponent(g);
g.setColor(Color.black);
if (startPoint != null && endPoint != null)
{
// draw the current dragged line
int x = Math.min(startPoint.x, endPoint.x);
int y = Math.min(startPoint.y, endPoint.y);
int width = Math.abs(endPoint.x - startPoint.x);
int height = Math.abs(endPoint.y - startPoint.y);
g.drawRect(x, y, width, height);
}
}
class MyMouseListener extends MouseInputAdapter
{
public void mousePressed(MouseEvent e)
{
if (SwingUtilities.isLeftMouseButton(e))
{
startPoint = e.getPoint();
repaint();
}
}
public void mouseReleased(MouseEvent e)
{
if (SwingUtilities.isLeftMouseButton(e))
{
startPoint = null;
endPoint = null;
//repaint();
}
}
public void mouseDragged(MouseEvent e)
{
if (SwingUtilities.isLeftMouseButton(e))
{
endPoint = e.getPoint();
repaint();
}
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
DrawSquare d = new DrawSquare();
frame.getContentPane().add( d );
frame.pack();
frame.setVisible(true);
}
}