Java Graphics,使用单击事件更改绘图的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22131342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:48:25  来源:igfitidea点击:

Java Graphics, changing the color of drawings using click event

javaswinggraphicscolorsmouseclick-event

提问by user3352349

Ok so basically I'm trying to write a GUI application which draws 2 circles and 2 rectangles in its main window. I'm trying to get it so that whenever the user clicks within the circles or rectangles, that particular circle or rectangle changes to another random colour.

好的,基本上我正在尝试编写一个 GUI 应用程序,它在其主窗口中绘制 2 个圆和 2 个矩形。我试图做到这一点,以便每当用户在圆形或矩形内单击时,该特定圆形或矩形就会更改为另一种随机颜色。

Currently I've got it so that the MouseClick event (anywhere on screen) causes all of the circles or rectangles to change colour, to the same colour. This is what I've got so far:

目前我已经得到了它,以便 MouseClick 事件(屏幕上的任何地方)导致所有圆形或矩形改变颜色,为相同的颜色。这是我到目前为止所得到的:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class Question2 {
    public static void main(String[] args) {
        SecondFrame f = new SecondFrame("Draw and Fill");
        f.init();
    }
}   

class SecondFrame extends JFrame{
    SecondFrame(String title) {
        super(title);
    }   

    private JPanel mainPanel;
    private GridBagConstraints gbc = new GridBagConstraints();
    private GridBagLayout gbLayout = new GridBagLayout();

    void init() {
        mainPanel = new JPanel();
        mainPanel.setLayout(gbLayout);
        this.setExtendedState(JFrame.MAXIMIZED_BOTH);
        this.setContentPane(mainPanel);
        gbc.gridheight = 1;

        mainPanel.addMouseListener(new MouseListener(){

            @Override
            public void mouseClicked(MouseEvent e) {
                Point mousePosition;
                mousePosition = mainPanel.getMousePosition();
                repaint();
            }

            @Override
            public void mouseEntered(MouseEvent e) {

            }

            @Override
            public void mouseExited(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mousePressed(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseReleased(MouseEvent arg0) {
                // TODO Auto-generated method stub

            }

        });

        this.pack();
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    public void paint(Graphics g){
     super.paint(g);
     Random ran = new Random();
     // Assumes max and min are non-negative.
     int red = 0 + ran.nextInt(255 - 0 + 1);
     int green = 0 + ran.nextInt(255 - 0 + 1);
     int blue = 0 + ran.nextInt(255 - 0 + 1);

     Color myColor = new Color(red,green,blue);
     g.setColor(myColor);
     g.fillOval(50,50,200,200);
     g.fillOval(50, 255, 200, 200);
     g.fillRect(255,50,200,200);
     g.fillRect(255, 255, 200, 200);
    }

}

If you could point me in the right direction that would be much appreciated. Thanks.

如果你能指出我正确的方向,我将不胜感激。谢谢。

采纳答案by tenorsax

You would keep a track of drawn object. Then check if click occurred within any of these objects. If yes, change its color. For example, you can use Shapeto represent simple forms. Its contains()method can be useful to determine if a clicked point is inside the boundary of the shape. Below is an example that introduces ShapeItemthat has two properties Shapeand Color. And, a panel that uses a list of ShapeItemto paint the actual shapes.

您将跟踪绘制的对象。然后检查是否在这些对象中的任何一个中发生了点击。如果是,请更改其颜色。例如,您可以使用Shape来表示简单的表单。它的contains()方法可用于确定单击的点是否在形状的边界内。下面是一个示例,它引入ShapeItem了两个属性ShapeColor。并且,一个使用 的列表ShapeItem来绘制实际形状的面板。

Also consider some minor side notes:

还要考虑一些次要的注意事项:

  • Don't paint directly on top level container such as JFrame. Instead, use JPanelor extension of JComponent;
  • For painting override paintComponent()rather than paint(), and don't forget to call super.paintComponent(g);
  • Usually there is no need to extend JFrame unless new functionality is added;
  • 不要直接在顶级容器上绘画,例如JFrame. 相反,使用JPanel或扩展JComponent;
  • 对于绘画覆盖paintComponent()而不是paint(),不要忘记调用super.paintComponent(g);
  • 通常不需要扩展 JFrame,除非添加新功能;

Take a look at Performing Custom Paintingtutorial, and Closer Look at the Paint Mechanismsection in particular, for more details.

查看执行自定义绘画教程,并特别仔细查看绘画机制部分,了解更多详细信息。

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class DemoShapes {
    public static final Color DEFAULT_COLOR = Color.BLUE;

    public DemoShapes() {
        List<ShapeItem> shapes = new ArrayList<ShapeItem>();
        shapes.add(new ShapeItem(new Rectangle2D.Double(110, 1, 100, 100),
                DEFAULT_COLOR));
        shapes.add(new ShapeItem(new Rectangle2D.Double(110, 110, 100, 100),
                DEFAULT_COLOR));
        shapes.add(new ShapeItem(new Ellipse2D.Double(1, 1, 100, 100),
                DEFAULT_COLOR));
        shapes.add(new ShapeItem(new Ellipse2D.Double(1, 110, 100, 100),
                DEFAULT_COLOR));

        JFrame frame = new JFrame("Shapes");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        ShapesPanel panel = new ShapesPanel(shapes);
        frame.add(panel);

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

    class ShapeItem {
        private Shape shape;
        private Color color;

        public ShapeItem(Shape shape, Color color) {
            super();
            this.shape = shape;
            this.color = color;
        }

        public Shape getShape() {
            return shape;
        }

        public void setShape(Shape shape) {
            this.shape = shape;
        }

        public Color getColor() {
            return color;
        }

        public void setColor(Color color) {
            this.color = color;
        }
    }

    class ShapesPanel extends JPanel {
        private List<ShapeItem> shapes;
        private Random rand = new Random();

        public ShapesPanel(List<ShapeItem> shapesList) {
            this.shapes = shapesList;

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {

                    Color color = getRandomColor();
                    for (ShapeItem item : shapes) {
                        if (item.getShape().contains(e.getPoint())) {
                            item.setColor(color);
                        }
                    }
                    repaint();
                }
            });
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2 = (Graphics2D) g.create();

            for (ShapeItem item : shapes) {
                g2.setColor(item.getColor());
                g2.fill(item.getShape());
            }

            g2.dispose();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 300);
        }

        private Color getRandomColor() {
            return new Color(rand.nextFloat(), rand.nextFloat(),
                rand.nextFloat());
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new DemoShapes();
            }
        });
    }
}

enter image description here

在此处输入图片说明

回答by delavega101

You should use mousePositionto determine if that point is within the bounds of any ovals or rectangles. If it is, perform g.setColor(myColor)and fill that shape. Then change gto a normal, non-randomized color, and fill the rest of the shapes.

您应该使用mousePosition来确定该点是否在任何椭圆形或矩形的边界内。如果是,请执行g.setColor(myColor)并填充该形状。然后更改g为正常的非随机颜色,并填充其余形状。