ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

如何在Java swing应用程序中保留和删除多个图形对象?

2019-10-09 07:14:10  阅读:199  来源: 互联网

标签:java image event-handling graphics swing


我有一个图像,并在其上使用预定义的位置来创建带有color的图形对象.用鼠标单击,我尝试在其上创建一些带有颜色的椭圆形.实际上,我无法实现这一目标.因为,当我单击一个预定义位置时,可以在其上创建一个椭圆形,但是当我单击另一个预定义位置时,第一个椭圆形消失了.

可以通过单击椭圆两次将其删除.

看看这个,

public class PrintDialog extends javax.swing.JDialog{
private int count = 0;
private int count_1 = 0;

/**
 * Creates new form PrintFeetDialog
 */
public PrintDialog(java.awt.Frame parent, boolean modal)
{
    super(parent, modal);
    initComponents();
    ImagePanel panel = new ImagePanel("Areas.jpg");
    this.getContentPane().add(panel);
    this.setResizable(false);
    this.setLocationRelativeTo(panel);
    this.pack();
}

private void formMouseClicked(java.awt.event.MouseEvent evt)                                  
{                                      
    // TODO add your handling code here:
    System.out.println("Print y - " + evt.getY());
    System.out.println("Print x - " + evt.getX());

    if ((evt.getX() >= 68 && evt.getX() <= 84) && (evt.getY() >= 44 && evt.getY() <= 72))
    {
        Graphics g = getGraphics();
        count++;
        if (count == 1)
        {
            g.setColor(Color.red);
            g.fillOval(66, 52, 20, 20);
            //  repaint();
        } else if (count > 1)
        {
            g.setColor(new Color(-3692899));
            g.fillOval(66, 52, 20, 20);
            repaint();
            count = 0;
        }
        g.dispose();
    }

    if ((evt.getX() >= 137 && evt.getX() <= 157) && (evt.getY() >= 50 && evt.getY() <= 75))
    {
        Graphics g1 = getGraphics();
        count_1++;
        if (count_1 == 1)
        {
            g1.setColor(Color.RED);
            g1.fillOval(137, 54, 20, 20);
        } else if (count_1 > 1)
        {
            g1.setColor(new Color(-3692899));
            g1.fillOval(66, 52, 20, 20);
            repaint();
            count_1 = 0;
        }
        g1.dispose();
    }
}
}   

图像面板类

public class ImagePanel extends JPanel{

private Image img;

public ImagePanel(String img, String str)
{
    //this(new ImageIcon(img).getImage());    
}

public ImagePanel(String path)
{
    Image img = new ImageIcon(path).getImage();
    this.img = img;
    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
    setPreferredSize(size);
    setMinimumSize(size);
    setMaximumSize(size);
    setSize(size);
    setLayout(null);

     try
    {
        BufferedImage image = ImageIO.read(new File(path));
        int rgb = image.getRGB(66, 52);
        System.out.println("Colour is: "+rgb);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
}

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    g.drawImage(img, 0, 0, null);
}
}

有什么想法吗?

谢谢 .

解决方法:

不要使用getGraphics,这不是自定义绘画的工作方式,有关更多详细信息,请参见Painting in AWT and SwingPerforming Custom Painting

基本思想是,您需要某种列表,您可以在其中添加每个形状.当发生mouseClicked时,您将遍历列表并检查是否单击的鼠标出现了其中一种形状,如果是,则将其从列表中删除,如果没有,则在单击该点时创建一个新形状,然后将其添加到列表中.

然后,您可以在paintComponent方法内部使用此List来物理绘制形状.

该示例扩展了您在自定义绘画中添加的ImagePanel

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new DrawPane("/Volumes/Disk02/Dropbox/MegaTokyo/thumnails/0.jpg"));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class ImagePanel extends JPanel {

        private Image img;

        public ImagePanel(String img, String str) {
            //this(new ImageIcon(img).getImage());    
        }

        public ImagePanel(String path) {
            Image img = new ImageIcon(path).getImage();
            this.img = img;
            try {
                BufferedImage image = ImageIO.read(new File(path));
                int rgb = image.getRGB(66, 52);
                System.out.println("Colour is: " + rgb);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return img == null ? new Dimension(200, 200) : new Dimension(img.getWidth(this), img.getHeight(this));          
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(img, 0, 0, null);
        }
    }

    public class DrawPane extends ImagePanel {

        private List<Shape> shapes;

        public DrawPane(String img, String str) {
            super(img, str);
            init();
        }

        public DrawPane(String path) {
            super(path);
            init();
        }

        protected void init() {
            shapes = new ArrayList<>(25);
            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    boolean clicked = false;
                    Iterator<Shape> it = shapes.iterator();
                    while (it.hasNext()) {
                        Shape shape = it.next();
                        if (shape.contains(e.getPoint())) {
                            it.remove();
                            clicked = true;
                            break;
                        }
                    }
                    if (!clicked) {
                        shapes.add(new Ellipse2D.Double(e.getX() - 10, e.getY() - 10, 20, 20));
                    }
                    repaint();
                }

            });
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g); 
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(Color.RED);
            for (Shape shape : shapes) {
                g2d.draw(shape);
            }
            g2d.dispose();
        }

    }

}

标签:java,image,event-handling,graphics,swing
来源: https://codeday.me/bug/20191009/1877615.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有