2015-03-31 115 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(); 
     } 
    }); 
}