2d java Graphics

时间:2013-07-02 16:45:33

标签: java swing graphics java-2d mouselistener

我是java 2d图形的新手,我有处理mouseclick事件的问题。 您是否有可能告诉我为什么在更新鼠标状态后点击后没有任何结果? 我想要做的是将数组中的图像更改为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;
}

1 个答案:

答案 0 :(得分:3)

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

addMouseListener(this);

除此之外:在Swing中实现自定义绘制时覆盖paintComponent而不是paint,并记得调用super.paintComponent(g)