鼠标位置和图形绘画

时间:2013-07-31 09:15:44

标签: java swing location paintcomponent mouse-listeners

这个程序假设每次我点击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的新手。如果我可以问,请详细回答。谢谢大家。

2 个答案:

答案 0 :(得分:2)

这些行应该使用mouseClicked方法,而不是actionPerformed

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

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

不相关但请务必调用super.paintComponent(g)作为paintComponent

的第一个陈述

答案 1 :(得分:1)

把它放在鼠标点击 MousePressed MouseReleased 方法

if(me.getX()>300)
            xX=xX+10;
repaint();