2012-07-11 5 views
2

안녕하세요, JPanel 하단에 빨간색 상자를 표시하려고합니다.이 상자를 화면의 한쪽 구석으로 이동하고 중지 한 다음 다른 방법으로 이동하기를 원합니다. 상자는 다음 멈추게 할 수없는 내가 프레임/패널 크기가 꺼져, 동적 어쩌면이를 계산하거나 final 값이 있어야위한Java timer & paintcomponent issues

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

public class JavaApplication13 extends JPanel { 

    public static void main(String[] args) { 
     JFrame rough = new JFrame("Panamr"); 
     rough.setVisible(true); 
     rough.setLocation(1, 1); 
     rough.setSize(500, 500); 
     rough.setContentPane(mamals); 
    } 

    public static int iomega(int x, int y) { 
     if (y == 1) { 
      diget = -5; 
      time.stop(); 
     } 
     if (y == 0) { 
      diget = 5; 
     } 
     return diget; 
    } 
    static JavaApplication13 mamals = new JavaApplication13(); 

    JavaApplication13() { 
     setBackground(Color.red); 
    } 
    static int oy = 400; 
    static int ox = 200; 
    static int diget; 
    static Timer time = new Timer(100, new ActionListener() { 

     public int xy = 1; 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      iomega(ox, xy); 
      if (ox == 500) { 
       xy = 1; 
      } 
      if (ox == 0) { 
       xy = 0; 
      } 
      ox = ox - iomega(ox, oy); 
      /*if(ox!=500){ 
      ox=ox-diget; 
      if(ox==0){ 
      diget=-5;} 
      else { 
      diget=5; 
      }    
      }*/ 
     } 
    }); 
    boolean test = true; 

    public void paint(Graphics g) { 
     super.paint(g); 
     g.setColor(Color.black); 
     g.fillRect(ox, oy, 60, 60); 
     time.start(); 
     repaint(); 
    } 
} 
+2

이 [Q & A] (http://stackoverflow.com/q/9849950/230513)를 참조하십시오. – trashgod

답변

2

당신의 공동 ordiantes 작업 된 코드입니다. 다음 xy = 0 및 xy = 1은 다음과 같이 바꿔야합니다.

if (ox == 400) {//this was a larger number then the panel/frame so it went offscreen 
      xy = 0;//swapped 
     } 
     if (ox == 0) { 
      xy = 1;//swapped 
     }