如何在jframe中清除

时间:2017-11-09 18:41:45

标签: java swing jframe

我有一个移动球的情况。然而,在与队列进行斗争后,repaint()将paintComponent(Graphics g)置于其中。我使用了paintImmediately。现在的问题是,如果无法访问super.paintComponent(g),我不知道如何在绘制前每次清除画布。因此,我的问题的一个可能的答案是一种清除画布的方法。我还发现Threads可能是一种可能的解决方案,但在经过多次尝试实现这个想法之后,我仍然不明白,如果有人能够显示正确的实现,我将非常感激。

这是我的代码:

  import java.awt.Graphics;
  import java.awt.Graphics2D;
  import java.awt.event.*;
  import javax.swing.JFrame;
  import javax.swing.JPanel;
  import java.awt.BorderLayout;
  import java.awt.Color;
  import javax.swing.JButton;

  public class PhysicsEngine extends JPanel {

  double x, y;

  JPanel pan;
  JButton b1;
  JButton b2;
  JButton b3;
  JButton b4;
  JButton b5;

  public static void main(String[] args) {

      JFrame frame = new JFrame("Ball Engine");
      PhysicsEngine gui = new PhysicsEngine();
      frame.add(gui, BorderLayout.CENTER);
      frame.setSize(600, 600);
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  }

  public PhysicsEngine() {

      b1 = new JButton("1");
      b1.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent event) {
              try {
                  startFirst();
              } catch (InterruptedException exception) {
              }
          }
      });
      this.add(b1);

      b2 = new JButton("2");
      b2.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
              try {
                  startSecond();
              } catch (InterruptedException exception) {
              }
          }
      });
      this.add(b2);

      b3 = new JButton("3");
      b3.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
              try {
                  startThird();
              } catch (InterruptedException exception) {
              }
          }
      });
      this.add(b3);

      b4 = new JButton("4");
      b4.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
              try {
                 startFourth();
              } catch (InterruptedException exception) {
              }
          }
      });
      this.add(b4);

      b5 = new JButton("5");
      b5.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e) {
              try {
                  startFifth();
              } catch (InterruptedException exception) {
              }
          }
      });
      this.add(b5);

  }

  public void paintComponent(Graphics g) {
      super.paintComponent(g);

      System.out.println("" + y);

      Graphics2D g2d = (Graphics2D) g;
      g2d.setColor(Color.RED);
      g2d.fillOval((int) x, (int) y, 30, 30);
  }

  public void startFirst() throws InterruptedException {
       x = 300;
       y = 80;

       // xPos= 0*t*t + 0*t + 300 this is constant at 300
       for(int t = 1; t<70;t++){

          y = .1 * t * t + 0 * t + 80; // parametric equation for y
          repaint();
          paintImmediately((int)x, (int)y, 30, 30);      
          Thread.sleep(10);
       }
  }

  public void startSecond() throws InterruptedException {
      x = 300;
      y = 550;

      for (int t = 1;t<150; t++) {
          // xPos= 0*t*t + 0*t + 300 this is constant at 300

          y = .1 * t * t - 15 * t + 550; // parametric equation for y
          repaint();
          paintImmediately((int)x, (int)y, 30, 30);
          Thread.sleep(10);
      }
  }

  public void startThird() throws InterruptedException {
      y = 550;
      x = 50;

      for (int t = 1;t<150; t++) {

          y = .1 * t * t - 15 * t + 550; // parametric equation for y
          x = 0 * t * t + 3 * t + 50; // parametric equation for x
          repaint();
          paintImmediately((int)x, (int)y, 30, 30);
          Thread.sleep(10);
      }
  }

  public void startFourth() throws InterruptedException {
      y = 50;
      x = -4;

      for (int t = 1;t<110; t++) {
          // xPos= 0*t*t + 0*t + 300 this is constant at 300

          y = .001*t * t * t + 50; // given parametric equation for y
          x = t - 4; // given parametric equation for x
          repaint();
          paintImmediately((int)x, (int)y, 30, 30);
          Thread.sleep(10);
      }
  }

  public void startFifth() throws InterruptedException {
      for (int t = 1; t < 130 /* goes for 1.5 seconds */; t++) {
          y = 200 * Math.sin(.05*t) + 300; // given parametric equation for y
          x = 200 * Math.cos(.05*t) + 300; // given parametric equation for x
          repaint();
          paintImmediately((int)x, (int)y, 30, 30);
          Thread.sleep(10);
      }
  }
  }

1 个答案:

答案 0 :(得分:1)

您的问题不在于#34;绘制队列&#34;,通过调用Thread.sleep,您违反了API的单线程特性在美国东部时间的背景下。

不应在for-loop中使用Thread.sleep,而应使用Swing Timer来更新变量paintComponent所依赖的状态(并调用repaint

Swing Timer可以被认为是一个伪循环,其ActionListener在EDT的上下文中被调用,从而可以安全地更新UI

首先查看Concurrency in SwingHow to Use Swing Timers了解更多详情

作为一个概念性的例子......

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private PhysicsPane physicsPane;

        public TestPane() {
            physicsPane = new PhysicsPane();
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = gbc.REMAINDER;
            JButton b1 = new JButton("1");
            b1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent event) {
                    startFirst();
                }
            });
            this.add(b1, gbc);
            this.add(physicsPane, gbc);
        }

        protected void startFirst() {
            physicsPane.startFirst();
        }

    }

    public class PhysicsPane extends JPanel {

        private Timer timer;
        private double xPos, yPos;
        private int tick;

        public PhysicsPane() {
            setBackground(Color.BLUE);
        }

        protected void stopTimer() {
            if (timer == null) {
                return;
            }
            timer.stop();
            timer = null;
        }

        public void startFirst() {
            stopTimer();

            xPos = 300;
            yPos = 500;
            tick = 0;

            timer = new Timer(10, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (tick >= 150) {
                        stopTimer();
                        return;
                    }

                    yPos = .1 * tick * tick - 15 * tick + 550;

                    tick++;
                    repaint();
                }
            });
            timer.start();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(600, 600);
        }

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(Color.RED);
            g2d.fillOval((int) xPos, (int) yPos, 30, 30);
            g2d.dispose();
        }
    }

}