I have started reading Performing custom paint with swing. I wanted to extend what I read on the tutorial and draw rectangle "live". Not just the rectangle to pop up and show on the panel, but I wanted visually see the Rectangle shape resize I drag the mouse, and finally when I release the mouse I wanted it to appear on the JPanel. I have added what I did so far with research and reading. The problem is since I am trying to catch each Rectangualr2D(this is the class I want to use) shape with mouse drag it end up looking like having a black background shape. How can I accomplish my target? Thanks for suggestions as always.
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
class RectTool {
public static void main(String args[]) {
JFrame frame = new JFrame();
frame.add(new DPanel());
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class DPanel extends JPanel {
ArrayList<Rectangle2D.Double> linesBasket = new ArrayList<Rectangle2D.Double>();
Rectangle2D.Double rect;
final static BasicStroke stroke = new BasicStroke(5.0f);
double p1d ;
double p2d;
public DPanel() {
setBorder(BorderFactory.createLineBorder(Color.black));
setBackground(Color.white);
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
final double startPointX = e.getX(); ;
final double startPointY = e.getY();
//current
rect.setRect(startPointX,startPointY,p1d,p2d);
}
public void mouseReleased(MouseEvent e){
linesBasket.add(rect);
}
});
addMouseMotionListener(new MouseAdapter(){
public void mouseDragged(MouseEvent e){
p1d = e.getX();
p2d = e.getY();
rect.setRect(10,10,p1d,p2d);
rect.setRect(rect);
repaint();
}
});
}
public void repaintShapeBasket(Graphics g){
rect = new Rectangle2D.Double();
rect.setRect(rect);
Graphics2D g2 = (Graphics2D) g;
linesBasket.add(rect);
for (Rectangle2D.Double rect : linesBasket) {
g2.draw(rect);
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
repaintShapeBasket(g);
}
}
