このビデオのようなアニメーションを実行するプログラムを作成しようとしていますが、正方形を追加するのに問題があります。すべての正方形を配列リストに追加しようとしましたが、どこに行くのかわかりませんでした。
これまでのところ、これは私のコードです:
public class Animation extends JFrame{ CrazySquares square = new CrazySquares(); Animation(){ add(new CrazySquares()); } public static void main (String[] args){ Animation frame = new Animation(); frame.setTitle("AnimationDemo"); frame.setLocationRelativeTo(null); // Center the frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(250, 250); frame.setVisible(true); } } class CrazySquares extends JPanel{ private final int numberOfRectangles=100; Color color=new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256)); private int x=1; private int y=1; private Timer timer = new Timer(30, new TimerListener()); Random random= new Random(); int randomNumber=1+(random.nextInt(4)-2); Random rand= new Random(); int rando=1+(rand.nextInt(4)-2); CrazySquares(){ timer.start(); } protected void paintComponent(Graphics g) { super.paintComponent(g); int width=getWidth(); int height=getHeight(); g.setColor(color); g.fillRect(x+width/2,y+(int)(height*.47), 20, 20); } class TimerListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { x += rando; y+= randomNumber; repaint(); } } }
2 に答える
1
ここに、1 つの長方形を描画するコードがあります。
int width=getWidth();
int height=getHeight();
g.setColor(color);
g.fillRect(x+width/2,y+(int)(height*.47), 20, 20);
ここで私がお勧めするのは、これらの値をSquare
オブジェクトに移植することです。または、さらに良いことに、Rectangle
オブジェクトを使用します。カスタムアプローチを使用した場合:
public class Square
{
public Square(int x, int y, int height, int width)
{
// Store these values in some fields.
}
public void paintComponent(Graphics g)
{
g.fillRect() // Your code for painting out squares.
}
}
次に、リスト内の各オブジェクトのpaintComponent
メソッドを呼び出すだけです。リストがあるとしましょう:
List<Square> squares = new ArrayList<Square>();
for(Square sq : squares)
{
sq.paintComponent(g);
}
于 2013-05-11T09:22:51.367 に答える