我想制作一个在屏幕上有对象的程序,然后当你按下它们时,它会跟随鼠标指针,直到你释放鼠标,然后它就不再跟随鼠标。
这是我必须将球添加到屏幕上的代码,所以如果可以调整代码,那就太好了。它分为3类
import java.awt.BorderLayout;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class DrawBalls {
JFrame frame = new JFrame();
final DrawPanel drawPanel = new DrawPanel();
JPanel controlPanel = new JPanel();
JButton createBallButton = new JButton("Add ball");
DrawBalls(){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
controlPanel.add(createBallButton);
frame.add(drawPanel);
frame.add(controlPanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
{
drawPanel.addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
for (Ball b : drawPanel.getBalls()) {
if (b.getBounds().contains(me.getPoint())) {
//this has it being the same coordinates as the mouse i don't know
//how to have it run constantly so when i move it, it doesn't work
b.setx(me.getX()-(b.radius/2));
b.sety( me.getY()-(b.radius/2));
drawPanel.repaint();
}
}
}
});
createBallButton.addActionListener(new ActionListener() {
Random rand = new Random();
private int counter = 1;
int noOfClicks = 1;
public void actionPerformed(ActionEvent e) {
if(noOfClicks<=10){
int ballRadius = 10;
int x = rand.nextInt(drawPanel.getWidth());
int y = rand.nextInt(drawPanel.getHeight());
//check that we dont go offscreen by subtarcting its radius unless its x and y are not bigger than radius
if (y > ballRadius) {
y -= ballRadius;
}
if (x > ballRadius) {
x -= ballRadius;
}
drawPanel.addBall(new Ball(x, y, ballRadius, counter));//add ball to panel to be drawn
counter++;//increase the ball number
noOfClicks++;
}
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new DrawBalls();
}
});
}
球类
import java.awt.*;
import java.awt.geom.*;
public class Ball {
private Color color;
private int x, y;
private int radius;
private final int number;
Ball(int x, int y, int radius, int counter) {
this.x = x;
this.y = y;
this.radius = radius;
this.number = counter;
this.color = Color.RED;
}
public void draw(Graphics2D g2d) {
Color prevColor = g2d.getColor();
g2d.drawString(number + "", x + radius, y + radius);
g2d.setColor(color);
g2d.fillOval(x, y, radius, radius);
g2d.setColor(prevColor);
}
public Rectangle2D getBounds() {
return new Rectangle2D.Double(x, y, radius, radius);
}
int getNumber() {
return number;
}
}
绘图面板
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class DrawPanel extends JPanel {
ArrayList<Ball> balls = new ArrayList<Ball>();
public void addBall(Ball b) {
balls.add(b);
repaint();
}
public ArrayList<Ball> getBalls() {
return balls;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (Ball ball : balls) {
ball.draw(g2d);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
}