如何在java swing应用程序中保留和删除多个图形对象? [英] How to keep and remove multiple graphic objects in java swing applications?

查看:93
本文介绍了如何在java swing应用程序中保留和删除多个图形对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图像,我使用预定义的位置来创建带有颜色的图形对象。用鼠标点击我尝试用颜色创建一些椭圆形。其实我无法达到这个目标。因为,当我点击一个预定义的位置时,我可以创建一个椭圆形,但是当我点击另一个预定义的位置时,首先椭圆形已经消失。



椭圆可以通过点击两次来删除它。



看看这个,

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

/ **
*创建新表单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在此处添加您的处理代码:
系统。 out.println(打印y - + evt.getY());
System.out.println(Print x - + evt.getX());

if((evt.getX()> = 68&  evt.getX()= 84)&(evt.getY()> = 44& & evt.getY()< = 72))
{
图形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))
{
图形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(Color is:+ rgb);
}
catch(IOException e)
{
e.printStackTrace();
}
}

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

有什么想法吗?



谢谢。

解决方案

不要使用 getGraphics ,这不是自定义绘画的工作原理,请参阅在AWT中绘画和Swing 执行自定义绘画了解更多详情



基本思想是,您需要添加每个形状的某种列表。当 mouseClicked 发生时,您将遍历列表并检查鼠标单击是否发生其中一个形状(如果是),则从列表,如果没有,您在点击点创建一个新的形状,并将其添加到列表



然后,使用 paintComponent 方法中的列表来物理绘制形状



此示例扩展了您的 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(){
尝试{
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(Color 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>形状;

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新的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();
}

}

}


I have an image and I use pre-defined positions on it to create graphic objects with colors . With a mouse click I try to create some ovals on it with colors . Actually I couldn't achieve this objective. Because , when I click on a pre-defined position I could create an oval on it but when I click on another pre-defined position first oval has gone.

An oval can be removed by click on it twice.

Have look at this ,

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();
    }
}
}   

image panel class

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);
}
}

Have any ideas please ?

Thank you .

解决方案

Don't use getGraphics, this is not how custom painting works, see Painting in AWT and Swing and Performing Custom Painting for more details

The basic idea is, you need some kind of List, into which you add each shape. When the mouseClicked occurs, you iterate through list and check to see if the mouse clicked occur one of the shapes, if it was, you remove the shape from the List, if not, you create a new shape at the point it was clicked and add it to the List.

You then use this List inside the paintComponent method to physically paint the shapes.

This example extends your ImagePanel adding in the custom painting

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 swing应用程序中保留和删除多个图形对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆