如何使用 mouseListener 显示数组中的内容? [英] How to display the contents in an array by using mouseListener?

查看:78
本文介绍了如何使用 mouseListener 显示数组中的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,其中包含在一个数组中的 8 个形状,当您单击鼠标时将显示这些形状.我是 Java 新手,对事件处理程序和侦听器不太熟悉.

我试图让形状出现在框架内鼠标点击的位置,但我遇到了麻烦,因为每个形状的构造函数都使用 2 个点作为参数.

这是代码中的一个示例:

import MyLibs.Circle;导入 MyLibs.Rectangle;导入 MyLibs.Shape;导入 java.awt.Color;导入 java.awt.Graphics;导入 java.awt.Image;导入 java.awt.Point;导入 java.awt.event.MouseAdapter;导入 java.awt.event.MouseEvent;导入 java.util.Random;公共类 DrawInScreenOnClickTest 扩展 javax.swing.JFrame {私有图像 dbImage;形状[] sh = 新形状[] {new Circle(new Point(50, 60), new Point(130, 180)),新矩形(新点(50, 200),新点(150, 350)),new Circle(new Point(200, 300), new Point(350, 350)),新矩形(新点(100, 100),新点(250, 250)),new Circle(new Point(150, 150), new Point(300, 300)),new Circle(new Point(200, 200), new Point(450, 500)),新矩形(新点(300, 300),新点(550, 550)),new Circle(new Point(150, 150), new Point(320, 320))};颜色 [] 颜色 = 新颜色 [] {Color.cyan, Color.green, Color.red, Color.blue, Color.magenta, Color.orange};随机随机=新随机();int i = 0;形状形状;布尔值第一 = 真;公共 DrawInScreenOnClickTest() {初始化组件();}私有无效 formMouseClicked(java.awt.event.MouseEvent evt){重绘();}公共类鼠标扩展 MouseAdapter {@覆盖public void mousePressed(MouseEvent e) {int x = e.getX();int y = e.getY();}}公共无效油漆(图形g){如果(第一个 == 真){第一个 = 假;} 别的 {int shapeColor = random.nextInt(6);形状 shape = sh[i];//调用形状数组shape.setColor(colors[shapeColor]);//随机调用颜色数组shape.drawShape(g);//显示形状如果(我== 4){我 = 0;} 别的我++;}}公共静态无效主(字符串参数[]){java.awt.EventQueue.invokeLater(new Runnable() {公共无效运行(){new DrawInScreenOnClickTest().setVisible(true);}});}}

解决方案

这里有一个示例,它交替绘制具有随机长度和宽度的形状(矩形和圆形).

这个例子使用 paintComponent(...) 方法在屏幕上绘制形状.

除非你改变它的行为,否则你不应该扩展 JFrame,而是构建你的 UI 来使用 JPanels,它更灵活,允许你使用 paintComponent.

我使用了 Shape API 而不是自定义的 Shape 类(您正在使用它,但您没有发布它的代码).

我没有包括随机颜色,因为这取决于 OP 来编写它,这只是一个关于如何在鼠标单击时绘制组件的示例.

import java.awt.Dimension;导入 java.awt.Graphics;导入 java.awt.Graphics2D;导入 java.awt.Rectangle;导入 java.awt.Shape;导入 java.awt.event.MouseAdapter;导入 java.awt.event.MouseEvent;导入 java.awt.geom.Ellipse2D;导入 java.util.ArrayList;导入 java.util.List;导入 javax.swing.JFrame;导入 javax.swing.JPanel;导入 javax.swing.SwingUtilities;公共类 DrawInScreenOnClickTest {私人 JFrame 框架;私人绘图窗格窗格;私人列表<形状>形状;公共静态无效主(字符串 [] args){SwingUtilities.invokeLater(new DrawInScreenOnClickTest()::createAndShowGUI);}私有无效 createAndShowGUI() {frame = new JFrame(getClass().getSimpleName());形状 = 新的 ArrayList();shape.add(new Ellipse2D.Double(50, 50, 50, 50));shape.add(new Rectangle.Double(50, 200, 50, 100));shape.add(new Ellipse2D.Double(150, 200, 150, 150));窗格 = 新绘图窗格();pane.addMouseListener(new MouseListen());框架.添加(窗格);框架.pack();frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setVisible(true);}@SuppressWarnings(串行")类 DrawingPane 扩展 JPanel {公共无效 addNewShape(Shape s) {}@覆盖受保护的无效paintComponent(图形g){super.paintComponent(g);Graphics2D g2d = (Graphics2D) g;对于(形状:形状){g2d.draw(s);}}@覆盖公共维度 getPreferredSize() {返回新维度(500, 500);}}类 MouseListen 扩展 MouseAdapter {整数计数器 = 0;@覆盖public void mouseClicked(MouseEvent e) {super.mouseClicked(e);计数器++;如果(计数器 % 2 == 0){shape.add(new Rectangle.Double(e.getX(), e.getY(), Math.random() * 50, Math.random() * 50));} 别的 {shape.add(new Ellipse2D.Double(e.getX(), e.getY(), Math.random() * 50, Math.random() * 50));}窗格重绘();}}}

附加(推荐)讲座:

I'm doing a program in which there are 8 shapes contained in an array that will be displayed when you click the mouse. I am new to Java and not that familiar with event handlers and listeners.

I am trying to make the shapes appear at the location the mouse is clicked at inside the frame yet I am having trouble since the constructor of each shape use 2 Points as its parameter.

Here's an example from the code:

import MyLibs.Circle;
import MyLibs.Rectangle;
import MyLibs.Shape;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;

public class DrawInScreenOnClickTest extends javax.swing.JFrame {

    private Image dbImage;

    Shape[] sh = new Shape[] {
        new Circle(new Point(50, 60), new Point(130, 180)),
            new Rectangle(new Point(50, 200), new Point(150, 350)),
            new Circle(new Point(200, 300), new Point(350, 350)),
            new Rectangle(new Point(100, 100), new Point(250, 250)),
            new Circle(new Point(150, 150), new Point(300, 300)),
            new Circle(new Point(200, 200), new Point(450, 500)),
            new Rectangle(new Point(300, 300), new Point(550, 550)),
            new Circle(new Point(150, 150), new Point(320, 320))
    };

    Color[] colors = new Color[] {
        Color.cyan, Color.green, Color.red, Color.blue, Color.magenta, Color.orange
    };

    Random random = new Random();
    int i = 0;
    Shape shape;
    boolean first = true;


    public DrawInScreenOnClickTest() {
        initComponents();
    }


    private void formMouseClicked(java.awt.event.MouseEvent evt) {
        repaint();
    }


    public class Mouse extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent e) {
            int x = e.getX();
            int y = e.getY();
        }
    }

    public void paint(Graphics g) {

        if (first == true) {
            first = false;
        } else {
            int shapeColor = random.nextInt(6);

            Shape shape = sh[i]; //calls shapes array
            shape.setColor(colors[shapeColor]); //call colors array random
            shape.drawShape(g); //display shape
            if (i == 4) {
                i = 0;
            } else
                i++;
        }
    }


    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new DrawInScreenOnClickTest().setVisible(true);
            }
        });
    }
}

解决方案

Here's an example that alternates drawing of shapes (rectangle and circle) with randomized lengths and widths.

This example makes use of paintComponent(...) method to draw shapes in the screen.

You shouldn't extend JFrame unless you're changing the behavior of it, instead build your UI towards the use of JPanels which are more flexible and allow you to use paintComponent.

I made use of the Shape API rather than a custom Shape class (which you're using and you didn't post the code for it).

I didn't included the randomized color as that's up to the OP to write it, this is just an example on how to draw components on mouse click.

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

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

public class DrawInScreenOnClickTest {
    private JFrame frame;
    private DrawingPane pane;
    private List<Shape> shapes;
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new DrawInScreenOnClickTest()::createAndShowGUI);
    }
    
    private void createAndShowGUI() {
        frame = new JFrame(getClass().getSimpleName());
        
        shapes = new ArrayList<Shape>();
        shapes.add(new Ellipse2D.Double(50, 50, 50, 50));
        shapes.add(new Rectangle.Double(50, 200, 50, 100));
        shapes.add(new Ellipse2D.Double(150, 200, 150, 150));
        
        pane = new DrawingPane();
        
        pane.addMouseListener(new MouseListen());
        
        frame.add(pane);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    
    @SuppressWarnings("serial")
    class DrawingPane extends JPanel {
        public void addNewShape(Shape s) {
            
        }
        
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            for (Shape s : shapes) {
                g2d.draw(s);
            }
        }
        
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(500, 500);
        }
    }

    class MouseListen extends MouseAdapter {
        int counter = 0;
        
        @Override
        public void mouseClicked(MouseEvent e) {
            super.mouseClicked(e);
            counter++;
            
            if (counter % 2 == 0) {
                shapes.add(new Rectangle.Double(e.getX(), e.getY(), Math.random() * 50, Math.random() * 50));
            } else {
                shapes.add(new Ellipse2D.Double(e.getX(), e.getY(), Math.random() * 50, Math.random() * 50));
            }
            pane.repaint();
        }
    }
}

Additional (recommended) lecture:

这篇关于如何使用 mouseListener 显示数组中的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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