Jframe - 绘制矩形不起作用

时间:2017-10-22 21:42:02

标签: java swing jframe jlayeredpane glasspane

我有这个代码,用于在预加载的图像上绘制一个矩形,但它不起作用。

当我将绘图类添加到框架时,它会覆盖图像,这意味着我无法看到我的预加载图像,但它仍然允许我绘制矩形。

此外,不是将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矩形坐标(根据系统输出getbounds2d)。

如果你删除了frame.add(new paintRectangles());,你可以看到框架的外观(但没有绘制矩形的能力)

2 个答案:

答案 0 :(得分:1)

一些问题突然出现。

首先,您显然不了解BorderLayout的工作原理以及如果您尝试将两个组件添加到同一位置,它将会怎样做。

其次,覆盖绘画不是推荐的自定义绘画方法,你应该使用paintComponent,除非你清楚地了解绘画是如何工作的,否则在你做任何事之前先调用super.paintComponent定制绘画。

第三,您似乎正在尝试将组件覆盖在滚动窗格的顶部,在其当前配置中,将阻止滚动窗格对鼠标事件做出反应。这也意味着如果滚动窗格的内容移动,您在顶部绘制的内容,不会随之滚动

我的&#34;将军&#39;建议是 - 阅读布局管理器,更好地了解它们的工作原理。阅读绘画系统在Swing中的工作原理,更好地了解如何使用它来实现所需的结果。从可以自己绘制图像的单个组件开始,然后您可以向其添加自定义绘画要求,这将大大减少您当前遇到的问题以及您将遇到的新问题

首先看看:

A&#34;简单&#34;解决你眼前的问题的办法就是加你&#34;画&#34;面板到JLabel。默认情况下,JLabel没有布局管理器,因此您需要提供一个,例如:

import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                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);

                lbl.setLayout(new BorderLayout());
                lbl.add(new PaintOverlayPane());

                JScrollPane jsp = new JScrollPane(lbl);
                frame.add(jsp);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

    public class PaintOverlayPane extends JPanel {

        ArrayList<Shape> shapes = new ArrayList<Shape>();
        Point startDrag, endDrag;

        public PaintOverlayPane() {
            setOpaque(false);
            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();
                }
            });
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g); //To change body of generated methods, choose Tools | Templates.
            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));
    }
}

这个问题的缺点是您无法控制图像的位置,也无法控制覆盖面板的尺寸,因此标签的尺寸可能会发生变化并且你的所有绘画都不再符合图标。

更好的解决方案是在同一个面板中绘制图像。通过这种方式,您可以完全控制图像的位置和形状的位置,并可以控制它们如何获得偏移,如果您愿意的话

答案 1 :(得分:0)

您可以将paintRectangles(应该是PaintRectangles btw)添加到JLayeredPane
解决方案并不理想,但它正在发挥作用 如果没有其他的话,值得尝试去了解这个选项:

public class DefineArea {

    public static void main(String[] args) throws IOException {

        displayImage();
    }
    private static void displayImage() throws IOException {

        //  URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
        //    BufferedImage image = ImageIO.read(url);
        //    ImageIcon icon= new ImageIcon(image);

        URL url = DefineArea.class.getResource("image.jpg");
        BufferedImage image = ImageIO.read(url);
        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);

        //add glass pane to layered pane
        JComponent glass = new paintRectangles();
        JLayeredPane lp = frame.getLayeredPane();
        int w = icon.getIconWidth(); int h = icon.getIconHeight();
        // Size is needed here, as there is no layout in lp
        //to make it useful you need to dynamically adjust glass size
        glass.setSize(w,h);
        lp.add(glass);

        frame.pack();
        frame.setVisible(true);
    }

    public static class paintRectangles extends JComponent {
        ArrayList<Shape> shapes = new ArrayList<>();
        Point startDrag, endDrag;

        public paintRectangles() throws IOException {

            addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    System.out.println("mousePressed");
                    startDrag = new Point(e.getX(), e.getY());
                    endDrag = startDrag;
                    repaint();
                }

                @Override
                public void mouseReleased(MouseEvent e) {
                    Shape r = makeRectangle(startDrag.x, startDrag.y, e.getX(), e.getY());
                    shapes.add(r);
                    startDrag = null;
                    endDrag = null;
                    repaint();
                }
            });

            addMouseMotionListener(new MouseMotionAdapter() {
                @Override
                public void mouseDragged(MouseEvent e) {
                    endDrag = new Point(e.getX(), e.getY());
                    repaint();
                }
            });
        }

        @Override
        protected void paintComponent(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));
    }
}

有关详细信息,请参阅How to Use Layered Panes

相关问题