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

Cannot see oval shape moving down the panel

我有这个程序,当用户点击面板时,椭圆形会向下移动面板。我使用 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());
        }
    }

您通过 sleep() 阻止了 Event Dispather Thread。请改用 javax.swing.Timer。在 actionPerformed() 中更改 y 并调用 repaint()

更新:

将 repaint() 放在 SwingUtilities.invokeAndWait() 中让 EDT 执行重绘

问题是,yPosition和形状一旦做出来就没有关系了(这和Java传递参数的方式有关,是一件好事),所以没有无论你怎么改变它,它都不会影响你的形状。

你也有多个形状,所以无论如何你都不希望它们都具有相同的值。

如您的 中所述,您需要遍历每个形状并更新其位置,例如...

for (Ellipse2D shape : shapes) {
    Rectangle2D bounds = shape.getBounds2D();
    double yPos = bounds.getY();
    yPos += 30;
    shape.setFrame(bounds.getX(), yPos, bounds.getWidth(), bounds.getHeight());
}
for(;;){   
if(horizontalBoundary){
    if((yPosition += 30) >= getHeight()-50){
        horizontalBoundary = false;
    }

}else if(!horizontalBoundary){
    if((yPosition -= 30)<= 0){
        horizontalBoundary = true;
    }
}
if(verticalBoundary){
    if((xPosition += 30) >= getWidth()-50){
        verticalBoundary = false;
    }
}else if(!verticalBoundary){
    if((xPosition -= 30) <= 0){
        verticalBoundary = true;
    }
}
System.out.println(yPosition + " " + xPosition);
  repaint();