我創建了一個程序,當我點擊屏幕時繪製一個圓圈。我有它的工作,以便我可以繪製儘可能多的圈子,我想要的。我甚至可以拖動一個圓圈而不是其他的圓圈,如果我硬編碼拖動的圓圈。該代碼是:爪哇拖動球
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.List;
import java.util.ArrayList;
public class DrawBall extends JPanel implements MouseListener, MouseMotionListener {
private List<Ball> balls;
private int x, y;
private int numBalls = 0;
boolean drag = false;
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Draw Ball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new DrawBall();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.setSize(300, 300);
frame.setVisible(true);
}
public DrawBall() {
super(new BorderLayout());
balls = new ArrayList<Ball>(10);
addMouseListener(this);
addMouseMotionListener(this);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RederingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for(Ball ball: balls) {
ball.paint(g2d);
}
g2d.dispose();
}
public void mouseClicked(MouseEvent event) {
x = (int) event.getPoint().getX();
y = (int) event.getPoint().getY();
Ball ball = new Ball(Color.red, numBalls, 30);
ball.setX(x);
ball.setY(y);
balls.add(ball);
numBalls = numBalls + 1;
repaint();
}
public void mousePressed(MouseEvent event) {
drag = true;
}
public void mouseReleased(MouseEvent event) {
drag = false;
}
public void mouseEntered(MouseEvent event) {}
public void mouseExited(MouseEvent event) {}
public void mouseDragged(MouseEvent event) {
if(drag == true) {
x = (int) event.getPoint().getX();
y = (int) event.getPoint().getY();
if(event.getSource() == balls.get(0)) {
Ball ball = balls.get(0);
ball.setX(x);
ball.setY(y);
balls.set(0,ball);
}
repaing();
}
}
public void mouseMoved(MouseEvent event) {}
public class Ball {
private Color color;
private int x, y, diameter, id;
public Ball(Color color, int id, int diameter) {
setColor(color);
setID(id);
setDiameter(diameter);
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public void setID(int id) {
this.id = id;
}
public void setDiameter(int diameter) {
this.diameter = diameter;
}
public void setColor(Color color) {
this.color = color;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public int getID() {
return id;
}
public int getDiameter() {
return diameter;
}
public Color getColor() {
return color;
}
protected void paint(Graphics2D g2d) {
int x = getX();
int y = getY();
g2d.setColor(getColor());
g2d.fillOval(x, y, getDiameter(), getDiameter());
}
}
}
我的問題是這樣的:在我的mouseDragged方法中,有一種簡單的方法來告訴我徘徊在哪個圈子?我玩過event.getSource(),但它似乎並沒有爲我的圈子工作,至少不是我所期望的。謝謝你的幫助。
我很害怕,這是我必須做的球。我希望有一個解決方案,我不必循環整個列表。噢,謝謝。 – nomad2986