-7

我想制作一个在屏幕上有对象的程序,然后当你按下它们时,它会跟随鼠标指针,直到你释放鼠标,然后它就不再跟随鼠标。

这是我必须将球添加到屏幕上的代码,所以如果可以调整代码,那就太好了。它分为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);
}

}

4

1 回答 1

2

一种方法是使您的 Ball 类成为实际的 Swing 组件。然后您可以使用ComponentMover类。

编辑:

你如何将一个类变成一个摇摆组件

基本上,您将 draw(...) 代码移动到 JComponent 的 paintComponent() 方法中。这是一个简单的示例,它为您完成所有自定义绘画,因为绘画基于 Shape 对象。您仍然需要修改代码以绘制“数字”。

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

public class ShapeComponent extends JComponent
{
    Shape shape;

    public ShapeComponent(Shape shape)
    {
        this.shape = shape;
        setOpaque( false );
    }

    public Dimension getPreferredSize()
    {
        Rectangle bounds = shape.getBounds();
        return new Dimension(bounds.width, bounds.height);
    }

    @Override
    protected void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;

        g2d.setColor( getForeground() );
        g2d.fill( shape );
    }

    @Override
    public boolean contains(int x, int y)
    {
        return shape.contains(x, y);
    }

    private static void createAndShowUI()
    {
        ShapeComponent ball = new ShapeComponent( new Ellipse2D.Double(0, 0, 50, 50) );
        ball.setForeground(Color.GREEN);
        ball.setSize( ball.getPreferredSize() );
        ball.setLocation(10, 10);

        ShapeComponent square = new ShapeComponent( new Rectangle(30, 30) );
        square.setForeground(Color.ORANGE);
        square.setSize( square.getPreferredSize() );
        square.setLocation(50, 50);

        JFrame frame = new JFrame();
        frame.setLayout(null);
        frame.add(ball);
        frame.add(square);
        frame.setSize(200, 200);
        frame.setVisible(true);

        MouseListener ml = new MouseAdapter()
        {
            public void mouseClicked( MouseEvent e )
            {
                System.out.println( "clicked " );
            }
        };

        ball.addMouseListener( ml );
        square.addMouseListener( ml );
    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowUI();
            }
        });
    }
}

这种方法与trashgod 建议使用图标的主要区别在于,鼠标事件只会在鼠标悬停在球上时生成,而不是球的矩形角,因为该contains(...)方法尊重您正在绘制的形状。

于 2013-03-10T18:46:15.337 回答