저는 Java와 OO 프로그래밍에 익숙하지 않습니다. 여기에 검은 색과 흰색 공이 움직이는 문제가 있습니다. 먼저 출력에서 원하는 프로그램을 설명하겠습니다 : 윈도우에 n 개의 볼 (예 : 6 개의 볼)이 있습니다. 하나는 검정색이고 하나는 흰색이고 각 이동마다 하나의 볼만 움직일 수 있습니다. 이 움직임 화면에으로 표시되어야하며 마지막에는 모든 흰색 공이 한쪽에 있어야하고 모든 검은 색 공이 다른쪽에 있어야합니다. 여기에 여섯 공의 예입니다 : 내가 프로그램을 작성했습니다검은 색과 흰색 공 이동
는 그것은 좋은 작업 보인다 알고리즘에는 결함,하지만 내 문제는 내가의 움직임의 애니메이션을 보여주지 수 있다는 것입니다 공, 각 운동에서 하나의 공이 그 이웃 공과 그 자리를 바꾸어야하지만, 나는 공의 최종 배열을 얻는다. 누군가 애니메이션 부분을 도와주세요. 나는 정말로 감사 할 것입니다.
코드 :
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.*;
public class DrawPanel extends JPanel implements ActionListener
{
Timer myTimer = new Timer(2000, this);
public static final int NUMBER_OF_CIRCLES = 10; //number of circles which are to moved
static int[] circles = new int[NUMBER_OF_CIRCLES];
public void paintComponent(Graphics g)
{
int x = 0; //start point of circles;
int length = 40; //diagonal of the circles
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
Ellipse2D circle;
//painting n circles based on the array
for(int index = 0; index<10; index++)
{
if(circles[index] == 0){ //if the element of the arrayy is 0 then draw a void circle
circle = new Ellipse2D.Double(x, 120, length, length);
g2.draw(circle);
}
else if(circles[index] == 1){ //if the element of the array is 1 them draw a filled circle
circle = new Ellipse2D.Double(x, 120, length, length);
g2.fill(circle);
}
x += 45; //increas start pont of the next circle 45 pixles
}
myTimer.start();
}
public void actionPerformed(ActionEvent e)
{
int tmp; //template for swaping elements
int condition; //condition of the forS
arrayFill(circles); //fills the array based on the writen method, one 1 and one 0 like: 0 1 0 1 0 1 0 1
//here is the part which works good, it changes palces of an elemen at time.
//at the end of this part the array would be like: 1 1 1 1 0 0 0 0
if(NUMBER_OF_CIRCLES % 2 == 0)
condition = circles.length/2 -1;
else
condition = circles.length/2;
for(int i = circles.length-1, k = 1; i>condition; i--, k++)
{
for(int j = i - k; j<i ;j++)
{
tmp = circles[j];
circles[j] = circles[j+1];
circles[j+1] = tmp;
//if we call arrayPrint method it will print the array but I don't know why repaint is not working here
//arrayPrint(circles);
repaint();
}
}
}
//fills the array, one 1 and one 0. Example: 0 1 0 1 0 1 0 1 0 1
public static void arrayFill(int[] array)
{
for(int i = 0; i<array.length; i++)
{
if(i%2 == 0)
array[i] = 0;
else
array[i] = 1;
}
}
}//end of class
그리고 주요 클래스 :
import javax.swing.JFrame;
public class BlackAndWhiteBallsMoving {
public static void main(String[] args)
{
DrawPanel myPanel = new DrawPanel();
JFrame myFrame = new JFrame();
myFrame.add(myPanel);
myFrame.setSize(600, 500);
myFrame.setTitle("Black And White Balls Moving");
myFrame.setVisible(true);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}//end of class
당신은'arrayFill (원)를 호출하고'각 틱, 그래서 당신은 항상 처음부터 다시하고 있습니다. – trashgod