I'm trying to use Graphics to draw a rectangle that select an area to crop an image, I can load the images and cut, but my rectangle doesn't draw in my form and I don't know why.
The program load images of a specific folder and pass the next with a button, then I select the part of imagen (here I have to see a rectangle), then I press "Recortar" and my cropped image is saved in other folder.
I have been reading and trying a lot of things and I haven't found a solution.
This is my code:
public class NewJFrame extends javax.swing.JFrame {
int z1=0;
int z2=0;
int z=0;
float x=0;
float y=0;
float ancho=0;
float alto=0;
Graphics2D g2D;
Image img;
BufferedImage img_bufi;
BufferedImage Imagmemoria;
BufferedImage imgrecortada;
public NewJFrame() {
add(new Dibujar()); //here I add Dibujar and this have paintComponent I want to use
initComponents();
setVisible(true);
super.repaint() ;
}
private void jLabel1MousePressed(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
x = evt.getX();
y = evt.getY();
}
private void jLabel1MouseDragged(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
ancho = evt.getX()-x;
alto = evt.getY()-y;
if(ancho<0) ancho=0;
if(alto<0) alto=0;
if(x > this.getWidth()) x = this.getWidth() - ancho ;
if(y > this.getHeight()) y = this.getHeight() - alto ;
System.out.println("X: "+x+" Y: "+y+" Ancho: "+ancho+" Alto: "+alto);
}
private void jLabel1MouseReleased(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
}
public class Dibujar extends JLabel{
@Override
public void paintComponent(Graphics g) {
//public void paint(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
if(img!=null){
Imagmemoria = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_RGB);
g2D = Imagmemoria.createGraphics();
g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2D.drawImage(img,0, 0, img.getWidth(this), img.getHeight(this), this);
g2D.setStroke(new BasicStroke(2f));
g2D.setColor(Color.WHITE);
Rectangle2D r2 = new Rectangle2D.Float( x, y, ancho, alto );
g2D.draw(r2);
g2.drawImage(Imagmemoria, 0, 0, this);
System.out.println("paintComponent");
}
}
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JLabel jLabel1;
// End of variables declaration
}