java - 看不到椭圆形沿着面板向下移动

标签 java swing arraylist awt

我有一个程序,当用户单击面板时,椭圆形将向下移动面板。我使用 System.out.print 打印了 yLocation(椭圆在 y 坐标上的位置),我可以看到值发生变化。但问题是我看不到椭圆形的移动。

public class OvalWithThreading {

public OvalWithThreading(){
    SwingUtilities.invokeLater(new Runnable(){

        @Override
        public void run() {
            JFrame frame = new JFrame("Click On The Canvas");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new OvalPane());
            frame.pack() ;
            frame.setVisible(true);
        }

    });
}
public static void main(String[] args) {
    new OvalWithThreading();
}

//Panel that will hold the oval shape
public class OvalPane extends JPanel{

    private int xPosition = 50;
    private int yPosition = 50;
    private int xSize = 50;
    private int ySize = 50;
    boolean clicked = true;
    boolean horizontalBoundary = true;
    boolean verticalBoundary = true;

    private List<Ellipse2D> shapes;

    public OvalPane(){
        shapes = new ArrayList<>();
        setBackground(Color.CYAN);
        addMouseListener(new MouseAdapter(){
            @Override
            public void mouseClicked(MouseEvent e){
                if(clicked) clicked = false;
                else if(!clicked) yPosition = 50; 

                shapes.add(new Ellipse2D.Double(xPosition, yPosition , 50, 50)); 
                System.out.print("Clicked");
                repaint();
            }

       });
   public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g.create();
        for (Ellipse2D shape : shapes) {
            g2d.fill(shape);
            Rectangle2D bounds = shape.getBounds2D();
            double yPos = bounds.getY();
            double xPos = bounds.getX();
            shape.setFrame(xPos, yPos, bounds.getWidth(), bounds.getHeight());
        }
    }

最佳答案

问题是,一旦形状做出来,yPosition就和形状没有任何关系了(这和Java传递参数的方式有关,是个好东西),所以无论多少你改变它,它不会影响你的形状。

您还有多个形状,因此您不希望它们都具有相同的值。

正如您的 previous question 中所述,您需要迭代每个形状并更新其位置,例如...

for (Ellipse2D shape : shapes) {
    Rectangle2D bounds = shape.getBounds2D();
    double yPos = bounds.getY();
    yPos += 30;
    shape.setFrame(bounds.getX(), yPos, bounds.getWidth(), bounds.getHeight());
}

关于java - 看不到椭圆形沿着面板向下移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35869293/

相关文章:

java - 这是一个已知的 IE 错误吗?未将提交参数传递给请求

java - 从jsp + Spring调用几个方法

Java Swing : prevent Components to update enabled state until I tell them to

java - 边框布局不起作用?

c++ - 为什么 placement new 第一次正确创建/添加对象但第二次却没有?

java - Java限制文件大小的方法

java - 初始化ArrayList为异步获取的ArrayList

根据用于源和目标的路径复制文件/目录时出现 java.lang.NullPointerException 错误

java - ArrayList 包含方法无法正常工作?

java - ArrayList 仅检测最后添加的对象的碰撞