Swing 如何使用MouseStener和press事件将填充的正方形更改为其他颜色?

Swing 如何使用MouseStener和press事件将填充的正方形更改为其他颜色?,swing,jpanel,mouseevent,background-color,Swing,Jpanel,Mouseevent,Background Color,这是家庭作业,我已经完成了大部分,但我仍停留在最后一步(实现一个鼠标事件,将我的一个随机彩色方块变为红色,而不是指定的颜色),我担心使用我的教授提供的方法不适用于此,因为他让我们在鼠标事件后重新绘制(我觉得我的代码只会用更多的随机颜色覆盖)。任何正确方向上的帮助或轻推都会有帮助,我确信这是一团混乱。 更新根据Camickr的协助,我的代码已更改为: import java.awt.GridLayout; import java.awt.Color; import java.awt.Dimensi

这是家庭作业,我已经完成了大部分,但我仍停留在最后一步(实现一个鼠标事件,将我的一个随机彩色方块变为红色,而不是指定的颜色),我担心使用我的教授提供的方法不适用于此,因为他让我们在鼠标事件后重新绘制(我觉得我的代码只会用更多的随机颜色覆盖)。任何正确方向上的帮助或轻推都会有帮助,我确信这是一团混乱。 更新根据Camickr的协助,我的代码已更改为:

import java.awt.GridLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.*;

// MouseListener Imports
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;


public class Test extends JPanel implements MouseListener
{

static Color[][] framework = new Color[8][8];
static int redCounter = 0;
// main Creates a JFrame and instantiates the 2d array of color objects
public static void main(String[] args)
{
    // The frame handles all the outside window work
    JFrame frame = new JFrame("MouseListener demo");

    // Allows the 'X' in the upper right to cause the program to exit
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


    //Create and set up the content pane.
    // contentPane holds a panel

    JComponent newContentPane = new Test();
    // MouseListenerDemo isa JPanel isa JComponent

    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);

    //Display the window.
    frame.pack();
    /* Causes this Window to be sized to fit the preferred size and layouts of its subcomponents. 
    The resulting width and height of the window are automatically enlarged if either of dimensions
    is less than the minimum size as specified by the previous call to the setMinimumSize method. 
    If the window and/or its owner are not displayable yet, both of them are made displayable before
    calculating the preferred size. The Window is validated after its size is being calculated.
    */

    frame.setVisible(true);
  for (int x = 0; x < framework.length; x++) {
for (int y = 0; y < framework.length; y++) {
  Color rc = randomColor();
    framework[x][y] = rc;
}
}

}

// Constructor
public Test()
{
    // layout the panel with an area in which to draw
    super(new GridLayout(0,1));
    // get Graphics object, which allows you to draw on the panel

    // set initial size of the panel
    setPreferredSize(new Dimension(400, 500));

    // ADD this JPanel to the list of components notified when a mouse event happens
    this.addMouseListener(this);

    // calls paint()
    repaint();
}

// draws the screen
public void paint(Graphics g)
{
    // Get the size
    Dimension d = this.getSize();
  int size = 50;    // The edge length of the squares
  int xSt = 50;    // Starting x-coordinate
  int ySt = 50;    // Starting y-coordinate
  int n = 8;        // n X n board
  int xPos, yPos;
  for(int row = 0; row < framework.length; row ++){
        for (int col = 0; col < framework.length; col ++){
         xPos = xSt*col;
         yPos = xSt*row;
         // set color
        g.setColor (framework[row][col]);
        // Draw square
        g.fillRect(xPos, yPos, size, size);
        }
  }
  g.setColor(Color.black);
  g.drawString("There are " + redCounter + " reds." , d.width/3, d.height);

}
   public static Color randomColor(){
    Random rg = new Random();
    int result = rg.nextInt(12); 
    Color color; 

    switch(result){
    case 0: color = Color.black;
    break;
    case 1: color = Color.blue;
    break;
    case 2: color = Color.cyan;
    break;
    case 3: color = Color.darkGray;
    break;
    case 4: color = Color.yellow;
    break;
    case 5: color = Color.green;
    break;
    case 6: color = Color.lightGray;
    break;
    case 7: color = Color.magenta;
    break;
    case 8: color = Color.orange;
    break;
    case 9: color = Color.pink;
    break;
    case 10: color = Color.red; redCounter = redCounter + 1;
    break;
    case 11: color = Color.white;
    break;
    default: color = Color.black;
    break;
    }
    return color;
   }


// MouseListener methods
public void mousePressed(MouseEvent evt) 
{
    // demonstrates how to use the parameter
    // to get the position of the mouse press
    Dimension d = this.getSize();
int x = evt.getX();
int y = evt.getY();
System.out.println(x+","+y);//these co-ords are relative to the component
System.out.println(evt.getSource());
for (int i = 0; i < framework.length; i++) {
            for (int j = 0; j < framework.length; j++) {
            System.out.println(framework[i][j]);
                if (evt.getSource().equals(framework[i][j])) {
                    framework[i][j] = Color.red;
                    redCounter = redCounter + 1;

                    }
                }
  }
    repaint(); // redisplay the frame by eventually calling the paint() method

}

// do nothing for the other mouse actions
public void mouseReleased(MouseEvent evt) {}
public void mouseClicked(MouseEvent evt) {}
public void mouseEntered(MouseEvent evt) {}
public void mouseExited(MouseEvent evt) {}
}
导入java.awt.GridLayout;
导入java.awt.Color;
导入java.awt.Dimension;
导入java.awt.Graphics;
导入java.util.Random;
导入javax.swing.*;
//进口滑鼠器
导入java.awt.event.MouseListener;
导入java.awt.event.MouseEvent;
公共类测试扩展JPanel实现MouseListener
{
静态颜色[][]框架=新颜色[8][8];
静态int redCounter=0;
//main创建一个JFrame并实例化颜色对象的2d数组
公共静态void main(字符串[]args)
{
//框架处理所有的外窗工作
JFrame=新的JFrame(“MouseListener演示”);
//允许右上角的“X”使程序退出
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//创建并设置内容窗格。
//contentPane包含一个面板
JComponent newContentPane=新测试();
//MouseListenerDemo isa JPanel isa JComponent
newContentPane.setOkable(true);//内容窗格必须是不透明的
frame.setContentPane(newContentPane);
//显示窗口。
frame.pack();
/*使此窗口的大小适合其子组件的首选大小和布局。
如果出现以下任一尺寸,则生成的窗口宽度和高度将自动放大
小于上一次调用setMinimumSize方法指定的最小大小。
如果窗口和/或其所有者尚不可显示,则这两个窗口在之前都可显示
计算首选大小。在计算窗口大小后验证窗口。
*/
frame.setVisible(true);
for(int x=0;x
我担心使用我的教授提供的方法不适合这种情况,因为他让我们在鼠标事件后重新绘制(我觉得我的代码将用更多随机颜色覆盖)

MouseEvent中的repaint()正确。但是,由于绘制代码不正确,将生成更多随机颜色

绘制方法应仅绘制组件的状态,而不更改状态。因此:

  • 你需要保留一个数据结构(比如2D数组)来保存每个单元格的颜色
    public void mousePressed(MouseEvent evt) 
    {
        // demonstrates how to use the parameter
        // to get the position of the mouse press
        Dimension d = this.getSize();
    int x = evt.getX()/50;
    int y = evt.getY()/50;
    framework[y][x] = Color.red;
    redCounter = redCounter+1;
    
    
        repaint(); // redisplay the frame by eventually calling the paint() method
    
    }