2015-03-31 117 views
0

现在我正在研究计算机科学测试的一些练习题,而且我遇到了一个只能给我带来麻烦的问题。我理解大部分摆动,但我不明白如何在面板上创建和移动形状。这是我迄今为止:如何在JPanel上移动形状?

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 

到目前为止,我创建了一个小红圈。但是,我如何使它横向跨屏?任何帮助是极大的赞赏。

+0

不要重写paint()。相反,你应该重载'paintComponent(...)'。 – camickr 2015-04-01 00:49:16

回答

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上执行所有动作和事情。 尝试在你的主要方法使用这个,而不是做一个新的SwingStarting

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