有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在JLabel上打印一个正方形,并将其存储在作为JLabel内容的图像中

我需要向用户显示一个图像,并引导他用鼠标选择一个区域。所以我创建并展示了一个JFrame,在其中我放置了一个用ImageIcon初始化的JLabel。 在我添加并覆盖JLabel上的mouseEventListner之后。我的工作计划是第一次和第二次点击鼠标,以获得相关点,作为识别选定区域的边。我正确地理解了要点。但我无法正确地将以前的JLabel更改为绘制了矩形的新JLabel

在JFrame中显示的图像(在其像素上)上存储所选区域的信息非常重要,因为我需要在像素级别管理这些信息

下面是我初始化JFrame的步骤:

 JFrame frame = new JFrame();
                ImageIcon icon = new ImageIcon(imgPath);
                JLabel label = new JLabel(icon);
                frame.add(label);
                frame.setTitle(imgPath.substring(imgPath.lastIndexOf("\\")+1));
                frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
                frame.setResizable(false); 

                //function to select area by mouse click
                addHandlerToDraw(label,frame,icon);

这就是我所说的函数:

private void addHandlerToDraw(JLabel label, JFrame frame, ImageIcon img) {

    label.addMouseListener(new MouseAdapter() {

        Point start = new Point();
        Rectangle captureRect;
        int k=0;
        @Override
        public void mouseClicked(java.awt.event.MouseEvent e) {
            if(k==0) {
                start = e.getPoint();
                k=1;
            } else {
                k = 0;
                Point end = e.getPoint();
                captureRect = new Rectangle(start, new Dimension(end.x-start.x, end.y-start.y));
            }
            repaint(captureRect, frame, img, label);
            label.repaint();
        }
    });

最后,这是一个功能,因为我想切换上一张图像(没有选定区域)和显示选定区域的图像:

private void repaint(Rectangle rect, JFrame frame, ImageIcon img, JLabel label) {

    BufferedImage bi = new BufferedImage(
            img.getIconWidth(),
            img.getIconHeight(),
            BufferedImage.TYPE_INT_RGB);

    Graphics2D g1 = bi.createGraphics();
    g1.setColor(new Color(200,30,30,45));
    if(rect != null) {
        g1.drawRect(rect.x, rect.y, rect.width, rect.height);
        frame.remove(label);
        frame.add(new JLabel(new ImageIcon(bi)));
        frame.setVisible(true);
    }}

正如我之前所说,即使我正确地计算了矩形,我也无法在新的JLabel和JFrame中存储和显示它。我错在哪里


共 (0) 个答案