以下代码的任何帮助...
我想用鼠标拖动图像来移动矩形,代码有什么问题。我是否需要绘制图像或 Jlabel 导致问题。
public class imagecrop extends JFrame {
int x,y,width=90, height=96 ;
public imagecrop(BufferedImage image) {
super("Crop");
getContentPane().setLayout(null);
setSize(546, 452);
JLabel lblNewLabel = new JLabel(corner(image));
lblNewLabel.setBounds(0, 0, 530, 382);
getContentPane().add(lblNewLabel);
JButton btnNewButton = new JButton("OK");
btnNewButton.setBounds(220, 393, 89, 21);
getContentPane().add(btnNewButton);
setVisible(true);
}
private ImageIcon corner(BufferedImage image) {
javaxt.io.Image image1 = new javaxt.io.Image(image);
image1.setHeight(382);
image=image1.getBufferedImage();
ImageIcon image2 = new ImageIcon(image);
addMouseMotionListener(new MouseAdapter()
{
@Override
public void mouseDragged(MouseEvent e) {
repaint();
x=e.getX();
y=e.getY();
}});
Graphics2D graph = (Graphics2D) image.getGraphics();
graph.draw((Shape) new Rectangle( x, y, width, height));
System.out.println(x+y);
return image2;
}
}
实际上
,您只需创建一次图像并将其存储在JLabel
中。之后,坐标将更改,但不会重新创建图像。
我建议 ot 覆盖JLabel
paintComponent()
方法并在该方法中调用g.draw((Shape) new Rectangle( x, y, width, height));
以反映更改。