您好,谢谢,
我正在与Graphics2D进行赌场游戏(轮盘赌)合作,所以我正尝试增加赌场筹码(金钱)的动作,因此我正在使用MouseDragged事件,并且作为测试,我仅使用1个椭圆
下面的代码
package roulette;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import javax.swing.JPanel;
import javax.swing.Timer;
public class RouletteInterface extends JPanel{
private List<Shape> money = new ArrayList<>();
public RouletteInterface() {
createEllipseGrap();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g4d = (Graphics2D) g.create();
paintEllipseGrap(g4d, g);
g4d.dispose();
}
protected void createEllipseGrap() {
Ellipse2D elipse = new Ellipse2D.Double(100, 100, 30, 30);
money.add(elipse);
addMouseListener(new moneyMouseListener());
addMouseMotionListener(new moneyMouseListener());
}
protected void paintEllipseGrap(Graphics2D g3d, Graphics g) {
g3d.setColor(Color.BLUE);
g3d.fill(money.get(0));
}
private class moneyMouseListener extends MouseAdapter {
int dragging;
private int x;
private int y;
@Override
public void mousePressed(MouseEvent e) {
if(money.get(0).contains(e.getPoint())) {
x = e.getX();
y = e.getY();
dragging = 0;
} else {
return ;
}
}
@Override
public void mouseDragged(MouseEvent e) {
if(dragging == 0) {
x = e.getX();
y = e.getY();
Ellipse2D elipse = new Ellipse2D.Double(x, y, 30, 30);
money.set(0, elipse);
repaint();
} else {
}
}
@Override
public void mouseReleased(MouseEvent m) {
dragging = 1;
repaint();
}
}
}
public class principal{
public static void main(String[] args) {
new principal();
}
public principal() {
JFrame frame = new JFrame();
frame.add(new RouletteInterface());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
出什么问题了?
即使我释放了mouseclick,MouseDragged事件仍会触发,因此当我在窗口的另一侧单击并拖动时,圆圈仍在与光标一起移动
答案 0 :(得分:0)
您的问题是您要添加两个不同的moneyMouseListeners实例作为MouseListener和MouseMotionListener:
addMouseListener(new moneyMouseListener());
addMouseMotionListener(new moneyMouseListener());
您必须那样做:
moneyMouseListener mListener = new moneyMouseListener();
addMouseListener(mListener);
addMouseMotionListener(mListener);
PS .:当使用仅用于分配“ 1”或“ 0”的变量(如“拖动”变量)时,应使用具有“ true”和“ false”的布尔变量;)
答案 1 :(得分:0)
此外,您可能要考虑使用Graphics的XOR模式绘制/绘制芯片,而不是一直调用repaint()。
这样,如果将芯片移到背景中的某个物体(或另一个芯片)上,则不会损坏另一个芯片或背景。