如何在我的绘画功能中循环一些东西?

时间:2017-10-10 00:17:32

标签: java mouselistener

所以我试图设置这个在悬停时改变图像的东西。我已经设置了mouseListener以了解鼠标是否在我的图像上。我有一个变量,其中存储了图像位置,当图像悬停时它会发生变化。当我的paint命令运行时,它会绘制默认图像,当我将鼠标悬停在它上面时,它不会改变,因为它没有再次绘制。如何更改图像位置时再次重新绘制它。 BTW mouseListener与图像的类不同。

我的形象:

private String settingsConfig = snake.settingsConfig;
settingsImage = new ImageIcon(getClass().getResource(settingsConfig));
settingsImage.paintIcon(this, g, 700, 23);

我的主要课程(绘画方法在其他课程中)

public class snake implements MouseListener{

public static int mouseX;
public static int mouseY;

public static String settingsConfig = "/assets/settings.png";

public static void main(String[] args) {

    // JFrame
    JFrame obj = new JFrame("Snake");
    gameplay Gameplay = new gameplay(); 
    obj.setBounds(10, 10, 905, 700);
    obj.setBackground(Color.DARK_GRAY);
    obj.setResizable(false);
    obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    obj.add(Gameplay);
    obj.setVisible(true);

    obj.addMouseMotionListener(new MouseAdapter() {
        @Override
        public void mouseMoved(MouseEvent e) {
            mouseX = e.getX();
            mouseY = e.getY();
            if(mouseX > 699 && mouseX < 761 && mouseY > 22 + 25 && mouseY < 54 + 25) {
                settingsConfig = "/assets/settingshover.png";
            }
            else {
                settingsConfig = "/assets/settings.png";
            }
        }
    });
}

非常小的一块油漆(图形g)(在另一个类别中):

public void paint (Graphics g) {

    if(moves == 0) {
        snakexlength[2] = 50;
        snakexlength[1] = 75;
        snakexlength[0] = 100;

        snakeylength[2] = 100;
        snakeylength[1] = 100;
        snakeylength[0] = 100;
    }

    if(moves >= 1) {
        playing = true;
    }

    // Draw title image border
    g.setColor(Color.WHITE);
    g.drawRect(24, 10, 851, 55);

    // Draw the title image and settings
    titleImage = new ImageIcon(getClass().getResource("/assets/snaketitle.jpg"));
    titleImage.paintIcon(this, g, 25, 11);

    settingsImage = new ImageIcon(getClass().getResource(settingsConfig));
    settingsImage.paintIcon(this, g, 700, 23);

    // Draw the border for gameplay
    g.setColor(Color.WHITE);
    g.drawRect(24, 74, 851, 577);

    // Draw background for the gameplay
    g.setColor(Color.BLACK);
    g.fillRect(25, 75, 850, 575);

    // Draw score
    g.setColor(Color.WHITE);
    g.setFont(new Font("arial", Font.PLAIN, 14));
    g.drawString("Score: " + score, 780, 30);

    // Draw  high score
    g.drawString("High Score: " + highScore, 780, 50);
}

1 个答案:

答案 0 :(得分:0)

  

如何在图像位置发生变化时再次重新绘制

在需要更新绘画的地方调用reapint();。例如,当您将鼠标悬停在图像上时,在侦听器中。

public void mouseMoved(MouseEvent e) {
    mouseX = e.getX();
    mouseY = e.getY();
    if(mouseX > 699 && mouseX < 761 && mouseY > 22 + 25 && mouseY < 54 + 25){
        settingsConfig = "/assets/settingshover.png";
    }
    else{
        settingsConfig = "/assets/settings.png";
    }
    repaint();  
}