我有这个程序,当用户点击面板时,椭圆形状将向下移动面板。我使用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());
}
}
当椭圆向下移动时,我可以看到没有椭圆,但是当它向上时,我看不到椭圆的移动。我所做的就是分配ypos = yPosition及其工作。但点击面板后创建的第一个椭圆将消失,第二个将生成动画。我想要的是我可以看到他们都向下和向上动画。我怎样才能做到这一点? –
我有多个椭圆滑落。如果您将yPosition分配给ypos,则它将不执行任何操作,因为值不会更改 – MadProgrammer
谢谢。但我怎么能做到这一点? –