1

该程序假设每次我在 x 坐标 300 或更大的位置单击屏幕时,将两个矩形向右移动 10 个点,但它没有,有什么问题?

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * To change this template use File | Settings | File Templates.
 */
public class MasterMind extends JComponent implements ActionListener,MouseListener {
    //private MouseEvent me;
    private int screenX=0;
    private int screenY=0;
    private ActionEvent e;
    private int xX=10;

    public MasterMind() throws  IOException {
    }

    public static void main(String [] args) throws IOException {
        JFrame window = new JFrame("Master Mind");
        MasterMind game= new MasterMind();
        window.add(game);
        window.pack();
        window.setLocationRelativeTo(null);
        window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        window.setVisible(true);
        Timer t =   new Timer(30, game);
        t.start();
        window.addMouseListener(game);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(800,600);
    }

    @Override
    protected void paintComponent(Graphics g) {
        g.setColor(Color.red);
        g.drawRect(xX,30,200,200);
        g.setColor(Color.red);
        g.drawString("x,y coordinates: "+screenX+" , "+screenY,400,100);

        g.setColor(Color.blue);
        g.drawRect(xX+3, 33, 194, 194);
    }

    @Override
    public void mousePressed(MouseEvent me) {    
    }
    @Override
    public void mouseReleased(MouseEvent me) {
        repaint();
    }
    @Override
    public void mouseEntered(MouseEvent me) {
    }
    @Override
    public void mouseExited(MouseEvent me) {
    }

    @Override
    public void mouseClicked(MouseEvent e) {
            MouseEvent mouseIvent = (MouseEvent) e;
            int screenX = mouseIvent.getX();
            int screenY = mouseIvent.getY();
            System.out.println("screen(X,Y) = " + screenX + "\t" + screenY);
            repaint();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //To change body of implemented methods use File | Settings | File Templates.
        if (screenX>300)  {
        xX=xX+10;  }
        //timer animation

        repaint();
    }
}

我对 Java 很陌生。所以如果我可以问,请详细回答。谢谢你们。

4

2 回答 2

2

这些行应该在mouseClicked方法中而不是在actionPerformed.

if (screenX > 300) {
    xX = xX + 10;
}

就在现有repaint方法之前。它们确保xX更新 X 坐标变量以供稍后在该paintComponent方法中使用。

无关,但请确保super.paintComponent(g)作为第一个语句调用paintComponent

于 2013-07-31T09:22:02.673 回答
1

把它放在你的MouseClickedMousePressedMouseReleased方法中

if(me.getX()>300)
            xX=xX+10;
repaint();
于 2013-07-31T09:27:55.747 回答