gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:51:00 24 4
gpt4 key购买 nike

我有一个程序,当用户单击面板时,椭圆形将向下移动面板。我使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com