如何在JPanel中移动形状?

时间:2015-03-31 22:53:32

标签: java swing

现在我正在研究计算机科学考试的一些练习题,而且我遇到了一个给我带来麻烦的东西。我大部分都了解摇摆,但我不了解如何在Panel中创建和移动形状。这就是我到目前为止所做的:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingStarting extends JFrame {
     public JPanel innerPanel; // panel containing moving shape
    public JButton pauseResumeButton;
    public static final int LEFT = 0;
    public static final int RIGHT = 1;
    public int direction = LEFT;
    // The dimensions of the inner panel. To simplify this problem,
    // assume the panel will always have these dimensions.
    public static final int PANEL_WIDTH = 600;
    public static final int PANEL_HEIGHT = 400;

    public Timer movementTimer = new Timer(10,new TimerListener());

    public SwingStarting() {

      innerPanel = new ShapePanel();
     innerPanel.setPreferredSize(
     new Dimension(PANEL_WIDTH,PANEL_HEIGHT));
     innerPanel.setBorder(
     BorderFactory.createLineBorder(Color.BLACK, 2));
     pauseResumeButton = new JButton("pause");

     add(innerPanel, BorderLayout.CENTER);
     JPanel buttonPanel = new JPanel(new FlowLayout());
     buttonPanel.add(pauseResumeButton);
     add(buttonPanel, BorderLayout.SOUTH);

     setDefaultCloseOperation(EXIT_ON_CLOSE);
     pack();

     setVisible(true);
     movementTimer.start();
    } // end constructor

    public class ShapePanel extends JPanel {
       public void paint(Graphics gc) {
         super.paintComponent(gc);
         int circleX = 0;
         int circleY = 100;
         gc.setColor(Color.RED);
         gc.fillOval(circleX,circleY,20,20);
        }
   } // end inner class



   public class TimerListener implements ActionListener {
     public void actionPerformed(ActionEvent e) {
        } // end actionPerformed
   } // end inner class

   public static void main(String args[]) {
     new SwingStarting();
    } // end main
 }// end class

到目前为止,我已经创建了一个小红圈。但是如何让它横向穿过屏幕?非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

在面板类中,为什么不使用Action侦听器制作计时器?

    // Make the shape here or earlier whenever you want.
    // By the way, I would change ShapePanel's paint method to paintComponent because it extends JPanel not JFrame
    // Create the object by giving ShapePanel a constructor
    ShapePanel s = new ShapePanel();
    ActionListener listener = new ActionListener()
    {
        public void actionPerformed(ActionEvent event)
        {
            // IN HERE YOU MOVE THE SHAPE
            s.moveRight();
            // Use any methods for movement as well.
            repaint();
        }
    };
    Timer timer = new Timer(5, listener);
    timer.start();

另外,因为你正在使用挥杆,所以你要确保在一个EDT上做所有的动作和事情。 尝试在main方法中使用它,而不是使用新的SwingStarting

public static void main(String[] args)
{
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() 
        {
           createAndShowGUI();
        }
    });
}