在鼠标释放时删除带有颜色的矩形

时间:2015-09-08 05:31:52

标签: java swing graphics

我正在开发一款游戏,在游戏的某些部分,我希望矩形在鼠标释放时消失。我在arrayList中放置了26个矩形,并在释放鼠标时删除单击的rectangle因此,如果删除fill方法,则矩形会成功消失,但如果fill方法存在,则不再有效。

这是我的paint方法:

   public void paintComponent(Graphics g)
   {  
      super.paintComponent(g);

        Image img = Toolkit.getDefaultToolkit().getImage(Rectangles2.class.getResource("background.jpg"));  
        g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);  

        Graphics2D g2 = (Graphics2D) g;

        for (Rectangle s : rectanglesList) {
            g2.draw(s);
        }

        g2.setColor(bColor);                    
        g2.fill(box1);                  
        g2.fill(box2);
        g2.fill(box3);
        g2.fill(box4);
        g2.fill(box5);
        g2.fill(box6);
        g2.fill(box7);
        g2.fill(box8);
        g2.fill(box9);
        g2.fill(box10);
        g2.fill(box11);
        g2.fill(box12);
        g2.fill(box25);
        g2.setColor(wColor);        
        g2.fill(box13);     
        g2.fill(box14);
        g2.fill(box15);
        g2.fill(box16);
        g2.fill(box17);
        g2.fill(box18);
        g2.fill(box19);
        g2.fill(box20);
        g2.fill(box21);
        g2.fill(box22);
        g2.fill(box23);
        g2.fill(box24);
        g2.fill(box26);
    }

以下是我删除rectangle(仅限摘录)的方法:

        if (box1.getBounds().contains(x, y)) {
            pickedPanelNum = 0;
            rectanglesList.remove(box1);
            panelsPane.repaint();
        }

以下是bColorwColor

的值
Color bColor = Color.BLACK;
Color wColor = Color.WHITE;

注意: pickedPanelNum仅用于分配int值,并且与问题无关。

我认为这是因为当我重新粉饰时,填充方法仍然存在。但是我不知道另一种绘制矩形的方法。

我希望我的问题清楚说明。如果您有任何想法我可以解决这个问题,请告诉我。谢谢!

更新 这是我的程序的一个较短的,可运行的版本。 (但不包括背景图片):

import java.awt.*;
import java.awt.Color.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.awt.geom.Rectangle2D;

public class Rec extends JComponent
{
    public ArrayList<Rectangle> rectanglesList = new ArrayList<Rectangle>();
    public int arrx[] = new int[120];
    public int arry[] = new int[120];
    JFrame frame = new JFrame();
    public int xSize = 2000;
    public int ySize = 1000;
    public int x;
    public int y;
    public int pickedPanelNum = 0;
    public String pickedPanelDash = "";
    public String pickedPanelColor = "";
    Color bColor = Color.BLACK;
    Color wColor = Color.WHITE;
    boolean removedPanel = false;

    public void launchFrame()
    {
        Random rand = new Random();
        for(int x = 0;x<120;x++)
        {
            arrx[x] = rand.nextInt(640);
            arry[x] = rand.nextInt(590);
        }

        Rectangle box1 = new Rectangle(arrx[103],arry[59],80,90);
        Rectangle box2 = new Rectangle(arrx[105],arry[3],80,90);

        rectanglesList.add(box1);
        rectanglesList.add(box2);

        JPanel mainPanel = new JPanel();

        JPanel panelsPane = new JPanel()
        {
           public void paintComponent(Graphics g)
           {  
              super.paintComponent(g);

                Image img = Toolkit.getDefaultToolkit().getImage(Rectangles2.class.getResource("background.jpg"));  
                g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);  

                Graphics2D g2 = (Graphics2D) g;

                for (Rectangle s : rectanglesList) {
                    g2.draw(s);
                }

                g2.setColor(bColor);                    
                g2.fill(box1);  
                g2.setColor(wColor);                    
                g2.fill(box2);
            }       
        };

        JPanel rightPane = new JPanel();    

        panelsPane.addMouseListener (new MouseAdapter ()
        {
            public void mousePressed(MouseEvent event)
            {
                x = event.getX();
                y = event.getY();                       
            }

            public void mouseReleased(MouseEvent event)
            {
                if (box1.getBounds().contains(x, y)) {
                    pickedPanelNum = 0;
                    rectanglesList.remove(box1);
                    panelsPane.repaint();
                }
                if (box2.getBounds().contains(x, y)) {
                    pickedPanelNum = 1;
                    rectanglesList.remove(box2);
                    panelsPane.repaint();
                }   
            }
        });

        panelsPane.addMouseMotionListener (new MouseAdapter ()
        {
            public void mouseDragged(MouseEvent event)
            {
                Rec obj = new Rec();
                int dx = event.getX() - x;
                int dy = event.getY() - y;

                if (box1.getBounds().contains(x, y)) {
                    box1.x += dx;
                    box1.y += dy;
                    panelsPane.repaint();
                }
                if (box2.getBounds().contains(x, y)) {
                    box2.x += dx;
                    box2.y += dy;
                    panelsPane.repaint();
                }

            x += dx;
            y += dy;

            }

            public void mouseReleased(MouseEvent event) {}
            public void mouseClicked(MouseEvent event) {}
            public void mouseEntered(MouseEvent event) {}
            public void mouseExited(MouseEvent event) {}
        }); 

        panelsPane.setPreferredSize(new Dimension (800, ySize-315));    
        rightPane.setPreferredSize(new Dimension (530, ySize-315)); 
        mainPanel.setPreferredSize(new Dimension (xSize, ySize));       
        frame.setPreferredSize(new Dimension (xSize, ySize));
        rightPane.setBackground(Color.gray);
        mainPanel.add(panelsPane);
        mainPanel.add(rightPane);
        frame.add(mainPanel);


        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);

    }

    public static void main(String args[])
    {
        Rec obj = new Rec();
        obj.launchFrame();
    }
}

1 个答案:

答案 0 :(得分:2)

即使您从box1移除了List,也没有什么可以阻止它填充paintComponent方法,for-loop只是绘制了列表中的矩形,但无论如何,你的代码都会隐式填充它们。

首先,摆脱所有box{n}个变量。接下来更改paintComponent方法...

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    //Image img = Toolkit.getDefaultToolkit().getImage(Rectangles2.class.getResource("background.jpg"));
    //g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
    Graphics2D g2 = (Graphics2D) g;

    for (Rectangle s : rectanglesList) {
        g2.setColor(bColor);
        g2.fill(s);
        g2.setColor(wColor);
        g2.draw(s);
    }
}

所以,这只是使用rectanglesList来首先绘制矩形并填充它们

然后,让我们更新mouseReleased ...

public void mouseReleased(MouseEvent event) {
    // Because the rectangles are painted in order, the later
    // rectangles are painted over the eailer ones, so, we reverse
    // the list so we can check for the higher positioned
    // rectangles
    List<Rectangle> copy = new ArrayList<>(rectanglesList);
    Collections.reverse(copy);
    for (Rectangle r : copy) {
        if (r.contains(event.getPoint())) {
            rectanglesList.remove(r);
            break;
        }
    }
    event.getComponent().repaint();
}

好吧,这更加时髦,但基本上,我们反转矩形列表(因为列表后面出现的那些矩形被绘制在它们之前出现的那些)并检查鼠标是否在任何内容中被点击其中之一。我们找到匹配的那一刻,我们突破循环并重新绘制生成事件的组件

而且,因为很高兴看到这些东西在运行,这是一个完整的例子......

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Rec extends JComponent {

    public ArrayList<Rectangle> rectanglesList = new ArrayList<Rectangle>();
    public int arrx[] = new int[120];
    public int arry[] = new int[120];
    JFrame frame = new JFrame();
    public int xSize = 2000;
    public int ySize = 1000;
    public int x;
    public int y;
    public int pickedPanelNum = 0;
    public String pickedPanelDash = "";
    public String pickedPanelColor = "";
    Color bColor = Color.BLACK;
    Color wColor = Color.WHITE;
    boolean removedPanel = false;

    public void launchFrame() {
        Random rand = new Random();
        for (int x = 0; x < 10; x++) {
            arrx[x] = rand.nextInt(640);
            arry[x] = rand.nextInt(590);
            rectanglesList.add(new Rectangle(arrx[x], arry[x], 80, 90));
        }

        JPanel mainPanel = new JPanel();

        JPanel panelsPane = new JPanel() {
            public void paintComponent(Graphics g) {
                super.paintComponent(g);

//              Image img = Toolkit.getDefaultToolkit().getImage(Rectangles2.class.getResource("background.jpg"));
//              g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), this);
                Graphics2D g2 = (Graphics2D) g;

                for (Rectangle s : rectanglesList) {
                    g2.setColor(bColor);
                    g2.fill(s);
                    g2.setColor(wColor);
                    g2.draw(s);
                }
            }
        };

        JPanel rightPane = new JPanel();

        panelsPane.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent event) {
                x = event.getX();
                y = event.getY();
            }

            public void mouseReleased(MouseEvent event) {
                // Because the rectangles are painted in order, the later
                // rectangles are painted over the eailer ones, so, we reverse
                // the list so we can check for the higher positioned
                // rectangles
                List<Rectangle> copy = new ArrayList<>(rectanglesList);
                Collections.reverse(copy);
                for (Rectangle r : copy) {
                    if (r.contains(event.getPoint())) {
                        rectanglesList.remove(r);
                        break;
                    }
                }
                event.getComponent().repaint();
            }
        });

        panelsPane.addMouseMotionListener(new MouseAdapter() {
            public void mouseDragged(MouseEvent event) {
            }

            public void mouseReleased(MouseEvent event) {
            }

            public void mouseClicked(MouseEvent event) {
            }

            public void mouseEntered(MouseEvent event) {
            }

            public void mouseExited(MouseEvent event) {
            }
        });

        panelsPane.setPreferredSize(new Dimension(800, ySize - 315));
        rightPane.setPreferredSize(new Dimension(530, ySize - 315));
        mainPanel.setPreferredSize(new Dimension(xSize, ySize));
        frame.setPreferredSize(new Dimension(xSize, ySize));
        rightPane.setBackground(Color.gray);
        mainPanel.add(panelsPane);
        mainPanel.add(rightPane);
        frame.add(mainPanel);

        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);

    }

    public static void main(String args[]) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                Rec obj = new Rec();
                obj.launchFrame();
            }
        });
    }
}