有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java限制和冻结按钮不起作用,也不会生成新球(动画)

这是一个UI,可以使球以对角线的方式向下移动,但每次我按下按钮“设置它的动画!”它不会创建新球

  • 另一个问题是“冻结”按钮不能像预期的那样工作,因为它应该停止球,然后;如果你再按一次,球就会再次移动

  • 最后,极限出了问题,因为当球几乎触到底部时,它没有到达底部并反弹到右侧。而且,当球“触到”正确的极限时,它就会上升

  • 此外,调整帧大小时,限制不会更新

请下载一个球并更改目录,以便程序可以找到球的分配位置。没有必要下载足球场,但如果你愿意,也可以。最后,我要感谢您花时间查找此故障

Ball link: https://lapequeteria.cl/wp-content/uploads/2018/11/balon-adidas-2.jpeg (Make it png)

Pitch link: https://www.freejpg.com.ar/asset/900/9c/9ca2/F100004898.jpg

import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import java.io.File;

class Animation extends JFrame {  //Frame

  static boolean running = true;
  static Layout panel = new Layout();
  JButton animate, stop;
  Runnable runnable;
  Thread move;

    public Animation() {
      setLayout(new BorderLayout());  //BorderLayout disposition
      setTitle("Pelota en acción");      

        animate = new JButton("Animate it!");  //Button to create balls
          animate.setSize(120,30);
          animate.addActionListener(new ActionListener(){
            @Override
              public void actionPerformed(ActionEvent e) {
                  panel.createEllipse();
                  runnable = panel;
                  move = new Thread(runnable);
                   panel.X = 0;
                   panel.Y = 0;
                  move.start();
               }
          });

        stop = new JButton("Freeze");  //Botón para interrumpir hilo (aun no implementado)
          stop.setBounds(0,0,120,30);
          stop.addActionListener(new ActionListener(){
            @Override
              public void actionPerformed(ActionEvent e) {
                if(move.isAlive()){
                  stop.setText("Go");  //Pause
                    synchronized(move) {
                      try {
//                        running = false;
                        move.wait();
                      } catch (InterruptedException ex) {
                        System.out.println("Interrupted");
                      }
                    }
                }
                else {
                  stop.setText("Freeze");  //Play
                    synchronized(move) {
//                      running = true;
                      move.notifyAll();
                    }
                }
              }
        });

        JPanel subPanel = new JPanel();  //Layout with its buttons situated to the south
          subPanel.add(animate);
          subPanel.add(stop);
        add(subPanel,BorderLayout.SOUTH);

        add(panel);
    }

    public static void main(String[] args) {  //Frame construction
        Animation ventana = new Animation();
          ventana.setSize(850,625);
          ventana.setLocationRelativeTo(null);
          ventana.setVisible(true);
          ventana.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}

class Layout extends JPanel implements Runnable {  //Layout and thread

  volatile double X,Y;  //Coordinates
  volatile double dX=1,dY=1;  //Direction
  static ArrayList<Image> balls = new ArrayList<>();  //Balls collection
  Image picture, ball;
  int width = 120,height = 120;

  @Override
    public void paintComponent(Graphics g) {  //Shows the ball and the pitch
      super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;

        soccerPitch();
        g2.drawImage(picture, 0, 0, null);
        for (Image ball : balls) {  //Balls added to the layout
          g2.drawImage(ball,(int)X,(int)Y,100,100,null);
        }
    }

    public void soccerPitch () {  //Builds the soccerPitch image
        try {
          picture = ImageIO.read(new File("C:\\Users\\Home\\Desktop\\NO BORRAR porfavor\\Cancha.jpg"));
        } catch (IOException ex) {
          System.out.println("Pitch image was not found");
        }
    }

    public void createEllipse () {  //Builds the ball image
        try {
          ball = ImageIO.read(new File("C:\\Users\\Home\\Desktop\\NO BORRAR porfavor\\Pelota.png"));
            System.out.println(ball.getWidth(null)+" "+ball.getHeight(null));
        } catch(IOException ex) {
          System.out.println("Any balls were found");
        }
        balls.add(ball);  //Balls are added to the collection
    }

    @Override
      public void run () {  //Moves the ball(coordinate system doesn't work)
        moveBall(Animation.panel.getBounds());
      }

    public void moveBall(Rectangle2D limits) {
        while(true) {
//        while(Animation.running) {
          System.out.println("X: "+X+"\tY: "+Y);
          System.out.println(limits.getBounds());
            X+=dX;  
            Y+=dY;

            if(X<limits.getMinX()){     
              X=limits.getMinX();   
              dX=-dX;
            }
            if(X + width>=limits.getMaxX()){    
              X=limits.getMaxX()-width; 
              dX=-dY;
            }
            if(Y<limits.getMinY()){ 
              Y=limits.getMinY();
              dY=-dY;
            }
            if(Y + height>=limits.getMaxY()){   
              Y=limits.getMaxY()-height;
              dY=-dY;
            }
            try {
              Thread.sleep(4);
            } catch (InterruptedException e) {
              System.out.println("Interrupted");
            }
            repaint();
        }
    }
}

万一你想帮我;我不是要求完成工作,只是解释一下为什么它不起作用


共 (1) 个答案

  1. # 1 楼答案

    你似乎违反了Concurrency in Swing的基本规则。另外,您可以手动设置组件的边界,而不是using LayoutManagers(这就是为什么调整框架大小时,组件不在正确的位置)

    现在,您在线程中启动应用程序,对吗?在这个线程中,您需要准备GUI并完成一些工作,然后在某个时候while(true)。当您while(true)时,线程将“卡在”while循环中,因此无法发生swing事件。这就是为什么您必须while(true)并在另一个线程中创建动画。但是,在Swing中创建动画的最佳方法是use a Swing Timer.

    我创建了一个示例,其中动画是每100ms在面板中创建一个新的随机矩形(10x10)。对它执行一些过期操作,并尝试将相同的逻辑调整到应用程序中(毕竟,您不会发布代码并期望我们为您修复:)

    例如:

    public class Animation extends JFrame implements ActionListener {
        private Timer timer;
        private RectanglePanel panel;
    
        public Animation() {
            super("test");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setLayout(new BorderLayout());
    
            add(panel = new RectanglePanel());
    
            timer = new Timer(100, this); //every 100 ms add new Shape
    
            JButton button = new JButton("Start Animation");
            button.addActionListener(e -> timer.start()); //start animation timer
            add(button, BorderLayout.PAGE_END);
            pack();
            setSize(500, 500);
            setLocationRelativeTo(null);
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            panel.createNewShape(); //add new shape
            panel.repaint();
        }
    
        private class RectanglePanel extends JPanel {
            private List<Rectangle> shapes;
    
            public RectanglePanel() {
                super();
                this.shapes = new ArrayList<>();
            }
    
            public void createNewShape() {
                int x = (int) (Math.random() * getWidth());
                int y = (int) (Math.random() * getHeight());
                x = Math.min(x, getWidth() - 10);
                y = Math.min(y, getHeight() - 10);
                Rectangle r = new Rectangle(x, y, 10, 10);
                System.out.println("New rectangle:" + r);
                shapes.add(r);
            }
    
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                for (Rectangle r : shapes) {
                    g.setColor(randomColor());
                    g.drawRect(r.x, r.y, r.width, r.height);
                }
            }
    
            private Color randomColor() {
                return new Color((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255));
            }
        }
    
        public static void main(String[] args) {
            //All swing applications must run on their own thread
            SwingUtilities.invokeLater(() -> new Animation().setVisible(true));
        }
    }
    

    预览:

    preview img