mousePressed后改变圆的颜色

时间:2014-09-15 21:04:20

标签: java swing mouselistener

我必须将地点的颜色更改为“红色”'当mousePressed时,它应该在mouseRelease时恢复到原来的颜色。这是我的代码:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class PanelTwo extends JPanel implements MouseListener{
    public Spot spot = new Spot(100,100,20);
    //public Color f = new Color(250,0,0);
    public PanelTwo(){
        super();
        setLayout (new FlowLayout());
        //setOpaque(true);
        addMouseListener(this);

    }
    public void paintComponent(Graphics g){
        spot.draw(g);
    }
    @Override
        public void mouseClicked(MouseEvent e) {
            // TODO Auto-generated method stub  
        }
    @Override
        public void mousePressed(MouseEvent e) {
            spot.x=e.getX();
            spot.y=e.getY();
            repaint();  
        }
    @Override
        public void mouseReleased(MouseEvent e) {
            // TODO Auto-generated method stub
        }
    @Override
        public void mouseEntered(MouseEvent e) {
            // TODO Auto-generated method stub  
        }
    @Override
        public void mouseExited(MouseEvent e) {
            // TODO Auto-generated method stub  
        }
}

还有另一个代码,其中包含有关我的形状的信息

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class Spot {
    public int x,y,r;
    public Color c= new Color(100,150,200);
    public Color f = new Color(250,0,0);
    public Spot(int X, int Y, int R){
        x=X; y=Y; r=R;
    }
    public void draw(Graphics g){
        g.setColor(c);
        g.fillOval(x-r, y-r, 2*r, 2*r);
    }
}

所以,我想在我按下鼠标后改变这个球的颜色,在我释放后 - 它应该恢复原来的颜色。

2 个答案:

答案 0 :(得分:1)

  • 调用mousePressed时,记录spot的原始颜色并更改其颜色
  • 调用mouseReleased时,将spot重置为原始颜色

答案 1 :(得分:0)

我假设你的班级中的两种颜色是点击和释放时的颜色。您无法更改颜色,因为您要将Graphics.setColor()方法设置为c的特定颜色。试着让它更灵活。

public class Spot {
    public int x,y,r;
    public Color c= new Color(100,150,200);
    public Color f = new Color(250,0,0);
    //make the default color to c
    public Color currentColor = c;
    public Spot(int X, int Y, int R){
        x=X; y=Y; r=R;
    }
    public void draw(Graphics g){
        g.setColor(currentColor);
        g.fillOval(x-r, y-r, 2*r, 2*r);
    }
}

并在mousePressedmouseReleased中更改currentColor

@Override
    public void mousePressed(MouseEvent e) {
        spot.x=e.getX();
        spot.y=e.getY();
        spot.currentColor = spot.f;
        repaint();  
    }
@Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub

        spot.x=e.getX();
        spot.y=e.getY();
        spot.currentColor = spot.c;
        repaint();  
    }