我有这段代码,旨在在预加载的图像上绘制一个矩形,但它不起作用。
当我将绘图类添加到框架时,它会覆盖图像,这意味着我看不到我预加载的图像,但它仍然允许我绘制矩形。
另外,不是将jframe放在我的屏幕中间,而是将它放在右上角,我必须最大化它才能看到框架。
编码:
public class defineArea {
public static void main(String[] args) throws IOException {
displayImage();
}
private static void displayImage() throws IOException {
BufferedImage image = ImageIO.read(new File("C:\\Users\\Rusty\\Desktop\\temp\\Test_PDF-1.png"));
ImageIcon icon = new ImageIcon(image);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel lbl = new JLabel();
lbl.setIcon(icon);
JScrollPane jsp = new JScrollPane(lbl);
frame.add(jsp);
frame.add(new paintRectangles());
frame.pack();
frame.setVisible(true);
}
public static class paintRectangles extends JComponent {
ArrayList<Shape> shapes = new ArrayList<Shape>();
Point startDrag, endDrag;
public paintRectangles() throws IOException {
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
startDrag = new Point(e.getX(), e.getY());
endDrag = startDrag;
repaint();
}
public void mouseReleased(MouseEvent e) {
Shape r = makeRectangle(startDrag.x, startDrag.y, e.getX(), e.getY());
shapes.add(r);
startDrag = null;
endDrag = null;
repaint();
}
});
this.addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
endDrag = new Point(e.getX(), e.getY());
repaint();
}
});
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = { Color.YELLOW, Color.MAGENTA, Color.CYAN, Color.RED, Color.BLUE, Color.PINK };
int colorIndex = 0;
g2.setStroke(new BasicStroke(2));
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.50f));
for (Shape s : shapes) {
g2.setPaint(Color.BLACK);
g2.draw(s);
g2.setPaint(colors[(colorIndex++) % 6]);
g2.fill(s);
}
if (startDrag != null && endDrag != null) {
g2.setPaint(Color.LIGHT_GRAY);
Shape r = makeRectangle(startDrag.x, startDrag.y, endDrag.x, endDrag.y);
g2.draw(r);
System.out.println(r.getBounds2D());
}
}
}
private static Rectangle2D.Float makeRectangle(int x1, int y1, int x2, int y2) {
return new Rectangle2D.Float(Math.min(x1, x2), Math.min(y1, y2), Math.abs(x1 - x2), Math.abs(y1 - y2));
}
}
任何人都可以帮忙吗?我基本上是在尝试从绘制的矩形中获取 2d Rectangle 坐标(根据系统 out getbounds2d)。
如果您删除 frame.add(new paintRectangles());,您可以看到框架的外观(但无法绘制矩形)