1

我是 java 2d 图形的新手,我在处理 mouseclick 事件时遇到问题。您是否可以告诉我为什么将鼠标状态更新为 clicked 后没有任何反应?我想要做的是将 0 2 处的数组中的图像更改为另一个图像。什么都没有发生。提前感谢您的帮助。

import java.awt.Graphics;
import java.awt.Graphics2D;

import java.awt.Image;
import java.awt.event.*;
import java.awt.*;

import javax.swing.ImageIcon;
import javax.swing.*;

public class Board extends JPanel implements MouseListener  {

private static boolean[] keyboardState = new boolean[525];
private static boolean[] mouseState = new boolean[3];
private static Image[][] images;


Image house;
int w = 0;
int h = 0;

int xPos;
int yPos;
    ImageIcon ii = new ImageIcon(this.getClass().getResource("house.gif"));
    ImageIcon iii = new ImageIcon(this.getClass().getResource("house1.gif"));

public Board() {
    house = ii.getImage();      
    h = house.getHeight(null);
    w = house.getWidth(null);
    images = new Image[10][10];
    for(int i = 0; i < 10; i++)
    {
        for(int j = 0; j < 10; j++)
        {
            images[i][j] = house;
        }        
    }
}

public void paint(Graphics g) {
    Graphics2D g2d = (Graphics2D) g;
    for(int i = 0; i < 10; i++)
    {
        for(int j = 0; j < 10; j++)
        {
            g2d.drawImage(images[i][j],w*i,h*j,null);                    
        }
    }
    //g2d.drawImage(house,15,15,null);
}

public void checkMouse()
{
    if(mouseState[0])
    {
        images[0][2] = iii.getImage();
        repaint();
        super.repaint();
    }
}   

@Override
public void mousePressed(MouseEvent e)
{
    mouseKeyStatus(e, true);
    checkMouse();
}

@Override
public void mouseReleased(MouseEvent e)
{
    mouseKeyStatus(e, false);
    repaint();
}

public static boolean mouseButtonState(int button)
{
    return mouseState[button - 1];
}

private void mouseKeyStatus(MouseEvent e, boolean status)
{
    if(e.getButton() == MouseEvent.BUTTON1)
        mouseState[0] = status;
    else if(e.getButton() == MouseEvent.BUTTON2)
        mouseState[1] = status;
    else if(e.getButton() == MouseEvent.BUTTON3)
        mouseState[2] = status;
}
4

1 回答 1

3

您需要MouseListener为您注册一个,Board JPanel以便mouseKeyStatus可以调用

addMouseListener(this);

旁白:重写paintComponent而不是paint在 Swing 中实现自定义绘画时,记住调用super.paintComponent(g).

于 2013-07-02T16:53:52.777 回答