使用鼠标滚轮改变鼠标所在矩形的颜色

Change color of the rectangle which the mouse is in by using the mouse wheel

抱歉发布了我的全部代码,但这样你可以更轻松地检查我的问题,不是吗?

package task3;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.*;

class Model {
    
    int l; //line
    int c; //column
    int[] loc = {0,0}; //location
    JFrame frame;
    int m_width;
    int m_height;
    int R;
    int G;
    int B;
    int count;
    int mY;
    int x, y;
    Rectangle rect;
    
    
    int genR() {
    int R = (int)(Math.random()*256);
        return R;
    }
    int genG() {
        int G = (int)(Math.random()*256); 
        return G;
    }
    int genB() {
        int B = (int)(Math.random()*256);
        return B;
    }
    
    public int getRectWidth() {
        return frame.getContentPane().getWidth() / c;
    }
    public int getRectHeight() {
        return frame.getContentPane().getHeight() / l;
    }
    
    
    Model(int width, int height, int line, int column, JFrame w) {
        m_width = width;
        m_height = height;
        l = line;
        c = column;
        frame = w;
    }
}

class Mvl extends JComponent implements MouseWheelListener {
    
    private Model m_Mod;
    
    Mvl(Model mod) {
        m_Mod = mod;
    }
    public void mouseWheelMoved(MouseWheelEvent e) {
        //m_Mod.mY += e.getWheelRotation();
        //m_Mod.mY += e.getUnitsToScroll();
        System.out.print(m_Mod.rect.getSize());
        m_Mod.frame.repaint();
        //int x = e.getXOnScreen();
        //int y = e.getYOnScreen();
        //int x = e.getX();
        //int y = e.getY();

       
         //RectangleComponent rc = new RectangleComponent(x, y);
         //m_Mod.frame.add(rc);
         //m_Mod.frame.revalidate();
    }
}

class Reactmouse implements MouseListener { //Print size of rectangle //Implement all methods otherwise abstract class
    
    private Model m_Mod;
    
    Reactmouse(Model mod) {
        m_Mod = mod;
    }
    
    public void mouseClicked(MouseEvent e) { 
        //System.out.println(++m_Mod.count + "  " + "Width: " + m_Mod.getRectWidth() + "  " + "Height: " +
        //m_Mod.getRectWidth() + " Position X-Axis: " + m_Mod.loc[0] + "Position Y-Axis: " + m_Mod.loc[1]);
        System.out.println("Position on X-Axis:" + e.getX() + " " + "Position on Y-Axis: "+  e.getY()); 
        //Cords of the click, in the rectangle
    }
    
    @Override
    public void mousePressed(MouseEvent e) {
        
    }
    @Override
    public void mouseReleased(MouseEvent e) {
            
    }
    @Override
    public void mouseEntered(MouseEvent e) {
            
    }
    @Override
    public void mouseExited(MouseEvent e) { 
        
    }
}

class View extends JComponent {
    
    private Model m_Mod;

    View(Model mod) {
        m_Mod = mod;
    }
    public void draw(Graphics g) {
        Color c = new Color(m_Mod.genR(), m_Mod.genG(), m_Mod.genB());
        g.setColor(c);
        g.fillRect(m_Mod.loc[0], m_Mod.loc[1], m_Mod.getRectWidth(), m_Mod.getRectHeight());
        m_Mod.rect = g.getClipBounds(); 
    }

在这里我要求尺寸的尺寸,但我需要矩形的尺寸

    @Override
    protected void paintComponent(Graphics g) {
        
        super.paintComponent(g);
    
        for(int i=0; i<m_Mod.l; ++i) {
            for(int j=0; j<m_Mod.c; ++j) {
                
              draw(g);  
              m_Mod.loc[0] = m_Mod.loc[0] + m_Mod.getRectWidth() + 2;
              
             }
            
            m_Mod.loc[0] = 0;
            m_Mod.loc[1] = m_Mod.loc[1] + m_Mod.getRectHeight() + 2;
        }
        m_Mod.loc[1] = 0;
    }
}
class Controller extends JFrame{
    
    private Model m_Mod;
    private View m_View;
    
    
        Controller(){
                
                JFrame window = new JFrame();
                m_Mod = new Model(500,500,8,8, window);
                m_View = new View(m_Mod);
                Image icon = window.getToolkit().getImage("C:\Users\49157\eclipse-workspace\Programmierung\src\task3\download.png");
                window.setIconImage(icon);
                window.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
                window.add(m_View);
                window.setSize(m_Mod.m_width,m_Mod.m_height);
                //window.add(new myButton());
                window.addMouseWheelListener(new Mvl(m_Mod));
                window.addMouseListener(new Reactmouse(m_Mod));
                window.setLocationRelativeTo(null);
                window.setVisible(true);
                window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                
        }
        void simulate(){
            m_View.repaint();
        }
        
}
public class task3 {

    public static void main(String[] args) throws Exception {
            
            Controller c = new Controller();    
            c.simulate();
            
        }
    }

好的,我可以用鼠标滚轮重绘整个框架,但我无法重绘此处绘制的单个矩形。我该怎么做?

主要问题是我不能要求我绘制的矩形的 x 和 y 坐标。有什么想法吗?

简介

由于您的代码不可运行,我继续创建了一个示例 GUI。这是示例 GUI。

这是我更改了几种颜色后的示例 GUI。

说明

Oracle 有一个有用的教程,Creating a GUI With Swing。跳过使用 NetBeans 学习 Swing IDE 部分。

当我创建 Swing GUI 时,我使用 model-view-controller (MVC) 模式。这种模式允许我将我的代码分成小的逻辑方法,让我一次专注于问题的一小部分。

MVC 模式意味着您首先创建模型,然后是视图,最后是控制器。您在模型、视图和控制器之间迭代。对于此 GUI,我创建了一个基本模型,并在进行过程中向该模型添加了字段。

在 Swing 中,MVC 模式意味着:

  • 视图从模型中读取信息。
  • 视图不更新模型。
  • 控制器更新模型和 repaint/revalidate 视图。

模型 classes 是普通的 Java getter/setter classes。查看 class 使用或扩展 Swing 组件。

通常,每个 Swing 动作或侦听器充当其自己的控制器,负责其模型和视图部分。没有一个控制器class“可以统治所有人”。

对于此应用程序,我创建了两个模型 classes、两个视图 classes 和两个鼠标侦听器 classes。

型号

ColorRectangleclass持有一个背景Color和一个java.awt.Rectangle持有矩形的位置和大小

ColoredRectanglesModel class 包含 two-dimensional 个 ColorRectangle 个实例数组和一个可能的背景颜色数组。这 class 创建视图用于创建 GUI 的模型。

查看

ColoredRectangles class 创建了 JFrame。这是一个非常标准的 JFrame 设置,它构成了我几乎所有 Swing 应用程序的开始。

所有 Swing 应用程序必须以调用 SwingUtilities invokeLater 方法开始。此方法确保 Swing 组件在 Event Dispatch Thread.

上创建和执行

DrawingPanelclass绘制矩形。时期。没有别的。

我覆盖了 paintComponent 方法。第一次调用 super.paintComponent 方法,它绘制 JPanel 背景并维护 Swing 绘制链。

控制器

RectangleListener class 让用户 select 将修改哪个矩形。

ColorListener class 使用鼠标滚轮滚动可能的背景颜色。

注意这两个 class 是多么简单。繁重的工作由模型 classes.

完成

代码

这是完整的可运行代码。我将所有额外的 classes 都放在 classes 中,这样我就可以 post 将代码作为一个块。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.util.Random;

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

public class ColoredRectangles implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new ColoredRectangles());
    }
    
    private final ColoredRectanglesModel model;
    
    private final DrawingPanel drawingPanel;
    
    public ColoredRectangles() {
        this.model = new ColoredRectanglesModel();
        this.drawingPanel = new DrawingPanel(this, model);
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Colored Rectangles");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.add(drawingPanel, BorderLayout.CENTER);
        
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }
    
    public void repaint() {
        drawingPanel.repaint();
    }
    
    public class DrawingPanel extends JPanel {

        private static final long serialVersionUID = 1L;
        
        private final ColoredRectanglesModel model;
        
        public DrawingPanel(ColoredRectangles view, ColoredRectanglesModel model) {
            this.model = model;
            this.setBackground(Color.BLACK);
            this.setPreferredSize(model.getDrawingDimension());
            this.addMouseListener(new RectangleListener(model));
            this.addMouseWheelListener(new ColorListener(view, model));
        }
        
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            
            Graphics2D g2d = (Graphics2D) g;
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
                    RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
                    RenderingHints.VALUE_FRACTIONALMETRICS_ON);
            
            ColorRectangle[][] coloredRectangles = model.getColoredRectangles();
            for (int i = 0; i < coloredRectangles.length; i++) {
                for (int j = 0; j < coloredRectangles[i].length; j++) {
                    g2d.setColor(coloredRectangles[i][j].getBackgroundColor());
                    Rectangle r = coloredRectangles[i][j].getRectangle();
                    g2d.fillRect(r.x, r.y, r.width, r.height);
                }
            }
        }
        
    }
    
    public class RectangleListener extends MouseAdapter {
        
        private final ColoredRectanglesModel model;

        public RectangleListener(ColoredRectanglesModel model) {
            this.model = model;
        }
        
        @Override
        public void mousePressed(MouseEvent event) {
            model.setSelectedRectangle(event.getPoint());
        }
        
    }
    
    public class ColorListener extends MouseAdapter {

        private final ColoredRectangles view;

        private final ColoredRectanglesModel model;

        public ColorListener(ColoredRectangles view,
                ColoredRectanglesModel model) {
            this.view = view;
            this.model = model;
        }

        @Override
        public void mouseWheelMoved(MouseWheelEvent event) {
            if (model.getSelectedRectangle() != null) {
                model.incrementColorIndex(event.getWheelRotation());
                ColorRectangle r = model.getSelectedRectangle();
                r.setBackgroundColor(model.getCurrentColor());
                view.repaint();
            }
        }

    }
    
    public class ColoredRectanglesModel {
        
        private int colorIndex;
        
        private final ColorRectangle[][] coloredRectangles;
        private ColorRectangle selectedRectangle;
        
        private final Color[] colors;
        private Color currentColor;
        
        private Dimension drawingDimension;
        
        private final Random random;
        
        public ColoredRectanglesModel() {
            this.colorIndex = 0;
            this.random = new Random();
            this.colors = generateColors();
            this.coloredRectangles = generateColoredRectangles();
            this.currentColor = colors[colorIndex];
        }
        
        private Color[] generateColors() {
            return new Color[] { Color.BLUE, Color.CYAN, Color.LIGHT_GRAY,
                    Color.MAGENTA, Color.ORANGE, Color.PINK, Color.RED,
                    Color.WHITE, Color.YELLOW };
        }
        
        private ColorRectangle[][] generateColoredRectangles() {
            ColorRectangle[][] coloredRectangles = new ColorRectangle[4][3];
            
            int x = 20;
            int y = 20;
            int width = 128;
            int height = 128;
            int maxWidth = 0;
            
            for (int i = 0; i < coloredRectangles.length; i++) {
                for (int j = 0; j < coloredRectangles[i].length; j++) {
                    int index = random.nextInt(colors.length);
                    Color color = colors[index];
                    coloredRectangles[i][j] = new ColorRectangle(color, x, y,
                            width, height);
                    x += width + 20;
                }
                maxWidth = x;
                x = 20;
                y += height + 20;
            }
            
            this.drawingDimension = new Dimension(maxWidth, y);
            
            return coloredRectangles;
        }
        
        public void setSelectedRectangle(Point point) {
            for (int i = 0; i < coloredRectangles.length; i++) {
                for (int j = 0; j < coloredRectangles[i].length; j++) {
                    Rectangle r = coloredRectangles[i][j].getRectangle();
                    if (r.x <= point.x && r.x + r.width >= point.x
                            && r.y <= point.y && r.y + r.height >= point.y) {
                        this.selectedRectangle = coloredRectangles[i][j];
                        return;
                    }
                }
            }

            this.selectedRectangle = null;
        }
        
        public void incrementColorIndex(int increment) {
            colorIndex += increment;
            if (colorIndex < 0) {
                colorIndex = colors.length + colorIndex;
            } else {
                colorIndex %= colors.length;
            }
            this.currentColor = colors[colorIndex];
        }

        public ColorRectangle[][] getColoredRectangles() {
            return coloredRectangles;
        }

        public Dimension getDrawingDimension() {
            return drawingDimension;
        }

        public ColorRectangle getSelectedRectangle() {
            return selectedRectangle;
        }

        public Color getCurrentColor() {
            return currentColor;
        }

    }
    
    public class ColorRectangle {

        private Color backgroundColor;

        private final Rectangle rectangle;

        public ColorRectangle(Color backgroundColor, int x, int y, int width,
                int height) {
            this.backgroundColor = backgroundColor;
            this.rectangle = new Rectangle(x, y, width, height);
        }

        public void setBackgroundColor(Color backgroundColor) {
            this.backgroundColor = backgroundColor;
        }

        public Color getBackgroundColor() {
            return backgroundColor;
        }

        public Rectangle getRectangle() {
            return rectangle;
        }

    }

}