我的应用程序可以裁剪图像。 我想实现的是根据从MouseListeners拍摄的坐标削减图像之前绘制的矩形。 这是我的代码:
public class ImageScreenShot extends JPanel implements MouseListener, MouseMotionListener {
ImagePanel im;
int drag_status = 0, c1, c2, c3, c4;
public int getC1() {
return c1;
}
public int getC2() {
return c2;
}
public int getC3() {
return c3;
}
public int getC4() {
return c4;
}
public void cut() {
im = new ImagePanel();
GraphicalUserInterface.getFrame().add(im);
im.addMouseMotionListener(this);
im.addMouseListener(this);
}
public void draggedScreen() throws Exception {
int w = c1 - c3;
int h = c2 - c4;
w = w * -1;
h = h * -1;
Robot robot = new Robot();
BufferedImage img = robot.createScreenCapture(new Rectangle(c1, c2, w, h));
File save_path = new File("screen1.jpg");
ImageIO.write(img, "JPG", save_path);
GraphicalUserInterface.getLabelIcon().setIcon(new ImageIcon(new ImageIcon(img).getImage().getScaledInstance(img.getWidth(),img.getHeight(),Image.SCALE_SMOOTH)));
JOptionPane.showConfirmDialog(null,"Would you like to save your cropped Pic?");
if(JOptionPane.YES_OPTION == 0){
PicChanges.getCurrentLabel();
} else {
PicChanges.getCurrentLabel();
}
System.out.println("Cropped image saved successfully.");
}
@Override
public void mouseClicked(MouseEvent arg0) {
}
@Override
public void mouseEntered(MouseEvent arg0) {
}
@Override
public void mouseExited(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent arg0) {
repaint();
c1 = arg0.getXOnScreen();
c2 = arg0.getYOnScreen();
}
@Override
public void mouseReleased(MouseEvent arg0) {
repaint();
if (drag_status == 1) {
c3 = arg0.getXOnScreen();
c4 = arg0.getYOnScreen();
try {
this.repaint();
draggedScreen();
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("Issue is under construction");
}
}
@Override
public void mouseDragged(MouseEvent arg0) {
repaint();
drag_status = 1;
c3 = arg0.getXOnScreen();
c4 = arg0.getYOnScreen();
}
@Override
public void mouseMoved(MouseEvent arg0) {
}
@Override
public void paint(Graphics g) {
super.paint(g);
int w = c1 - c3;
int h = c2 - c4;
w = w * -1;
h = h * -1;
if (w < 0)
w = w * -1;
g.setColor(Color.RED);
g.drawRect(c1, c2, w, h);
System.out.println("paint component");
}
}
public class ImagePanel extends JPanel {
private BufferedImage imageToCut;
public ImagePanel() {
Dimension size = new
Dimension(GraphicalUserInterface.getLabelIcon().getSize());
setPreferredSize(size);
setMaximumSize(size);
setMinimumSize(size);
setSize(size);
}
@Override
protected void paintComponent(Graphics g) {
g.drawImage(imageToCut, 0, 0, null);
System.out.println("painted");
}
}
我很困惑,我无法弄清楚如何调用paint()
方法,这就是为什么截至目前,图像被裁切并正确,但矩形被绘制。 据我了解我paintComponent()
方法工作,我调用ImagePanel类,并添加MouseListeners
它在repaint()
方法被调用。
要调用paint()
方法,我需要调用ImageScreenShot
类,但这里的问题出现在哪里。
所以我的问题是,如何调用paint()
被调用的方法repaint()
方法在MouseListeners
的ImageScreenShot
类?