2013-08-07 4 views
0

나는 사각형을 그려서 화면을 가로 질러 움직이는 paint 방법을 가지고 있습니다. 사각형을 화면 밖으로 옮길 때 화면에서 벗어나기를 원합니다. JFrame의 시작 부분으로 돌아갑니다. 나는 그것이 if(rectangle.isoffthescreen){ put it back on the screen }과 같을 것이라고 추측하지만 나는 그것을 어떻게하는지 모른다. 또한, 직사각형에 대해 JFrame frame = new JFrame();과 같은 것을 할 수 있는지 알고 싶지만 사각형에 대해서는 분명합니다. 혼란스러워서 미안해. 지금까지Graphics2D의 무언가가 프레임에서 벗어나는 지 확인하는 방법

public class main extends JPanel { 

public static int place = -350; 
public Rectangle rect; 
public int xDelta; 
    public main() { 

     rect = new Rectangle(0, 75, 50, 50); 
     xDelta = 4; 
     Timer timer = new Timer(40, new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       rect.x += xDelta; 
       if (rect.x + rect.width > getWidth() - 1) { 
        rect.x = getWidth() - rect.width; 
        xDelta *= -1; 
       } else if (rect.x < 0) { 
        rect.x = 0; 
        xDelta *= -1; 
       } 
       repaint(); 
      } 
     }); 
     timer.start(); 

    } 

public void paint(Graphics g) { 
    super.paint(g); 
    Graphics2D g2d = (Graphics2D) g.create(); 
    Random r = new Random(); 
    int r1; 

    r1 = r.nextInt(5); 
    if (r1 == 0) { 
     g2d.setColor(Color.WHITE); 
    } else if (r1 == 1) { 
     g2d.setColor(Color.BLUE); 
    } else if (r1 == 2) { 
     g2d.setColor(Color.RED); 
    } else if (r1 == 3) { 
     g2d.setColor(Color.GREEN); 
    } else if (r1 == 4) { 
     g2d.setColor(Color.PINK); 
    } else { 
     g2d.setColor(Color.CYAN); 
    } 

    place += 50; 

    rect = new Rectangle(place, 100, 300, 200); 
    g2d.draw(rect); 
    g2d.fill(rect); 
    g2d.dispose(); 

    try { 
     Thread.sleep(400); 
    } catch (Exception e) { 
    } 

    repaint(); 

} 
} 

public class frame { 

public static JFrame frame; 


public static void main(String args[]){ 
    frame = new JFrame(); 
    frame.setSize(500, 500); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    //frame.setResizable(false); 
    frame.setVisible(true); 
    frame.setLocationRelativeTo(null); 
    main m = new main(); 
    m.setBackground(Color.BLACK); 
    frame.add(m); 
} 


} 

에서 나는 내가 여전히 동작하지 않습니다 수있는 다음

@MadProgrammer이다.

답변

2

첫째, 당신은 최고 수준의 컨테이너의 최우선 paint을 피해야한다 대신 JComponent에서이 확장 것을 사용 (같은 JPanel)하고 paintComponent의 우선합니다.

여러 가지 이유가 있지만, 귀하의 경우 프레임에는 볼 수있는 영역 내에있는 장식이 들어 있습니다.

기본 프로세스

if (box.x + box.width > getWidth() - 1) { 
    // The boxes right edge is beyond the right edge of it's container 
} else if (box.x < 0) { 
    // The boxes left edge is beyond the left edge of it's container 
} 

이것은 box의 왼쪽 가장자리 넘어의 우측 에지가 용기 오른쪽 가장자리를 넘어서 box이 경우는 '있는지 확인 ... 에지 경우를 확인하는 것 컨테이너의 좌단

수직 검사도 포함하면 간단합니다.

은 ... 여러 가지가 저를 걱정

즉시 영업 이익의 예제 코드에서 예제

  1. 재정 paint
  2. 부름을

    import java.awt.BorderLayout; 
    import java.awt.Color; 
    import java.awt.Dimension; 
    import java.awt.EventQueue; 
    import java.awt.Graphics; 
    import java.awt.Graphics2D; 
    import java.awt.Rectangle; 
    import java.awt.event.ActionEvent; 
    import java.awt.event.ActionListener; 
    import javax.swing.JFrame; 
    import javax.swing.JPanel; 
    import javax.swing.Timer; 
    import javax.swing.UIManager; 
    import javax.swing.UnsupportedLookAndFeelException; 
    
    public class Move { 
    
        public static void main(String[] args) { 
         new Move(); 
        } 
    
        public Move() { 
         EventQueue.invokeLater(new Runnable() { 
          @Override 
          public void run() { 
           try { 
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
           } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
           } 
    
           JFrame frame = new JFrame("Testing"); 
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
           frame.setLayout(new BorderLayout()); 
           frame.add(new TestPane()); 
           frame.pack(); 
           frame.setLocationRelativeTo(null); 
           frame.setVisible(true); 
          } 
         }); 
        } 
    
        public class TestPane extends JPanel { 
    
         private Rectangle box; 
         private int xDelta; 
    
         public TestPane() { 
    
          box = new Rectangle(0, 75, 50, 50); 
          xDelta = 4; 
          Timer timer = new Timer(40, new ActionListener() { 
           @Override 
           public void actionPerformed(ActionEvent e) { 
            box.x += xDelta; 
            if (box.x + box.width > getWidth() - 1) { 
             box.x = getWidth() - box.width; 
             xDelta *= -1; 
            } else if (box.x < 0) { 
             box.x = 0; 
             xDelta *= -1; 
            } 
            repaint(); 
           } 
          }); 
          timer.start(); 
    
         } 
    
         @Override 
         public Dimension getPreferredSize() { 
          return new Dimension(200, 200); 
         } 
    
         @Override 
         protected void paintComponent(Graphics g) { 
          super.paintComponent(g); 
          Graphics2D g2d = (Graphics2D) g.create(); 
          g2d.setColor(Color.BLUE); 
          g2d.fill(box); 
          g2d.dispose(); 
         } 
        } 
    
    } 
    

    업데이트 업데이트 방법 밖으로 Performing Custom Painting 그림에 대한 자세한 내용은에서의 paint 방법

  3. place 변수

확인에 의존하여 새로운 Rectangle 만들기

  • 내에서 repaint를 호출 paint 방법
  • 에서스윙

    Event Dispatching Thre를 장시간 실행하지 마십시오. 광고를 사용하면 EDT가 (다른 것들 사이에서) 페인트 요청 및 새 이벤트를 처리하지 못하게합니다. paint 메서드에서 Thread.sleep을 호출하면 스윙이 화면을 업데이트하지 못하게됩니다.

    자세한 내용은 Concurrency in Swing을 확인하십시오.

    repaint (또는 repaint을 호출 할 수있는 방법)을 paint 방법으로 호출하는 것이 CPU주기를 소모하는 확실한 방법입니다.

    당신은 효과적으로 당신이 직사각형 멈추는 Timer이 만든 것을, 당신이 어떤 변화를 버리고있는 paint 방법에 새로운 Rectangle을 만들면 스윙

    에서 페인트 프로세스에 대한 자세한 내용은 Painting in AWT and Swing을 체크 아웃 할 수 있습니다 효과적으로 이동하는 것 ...

    place 방법은 필요하지 않습니다. 애니메이션은 시간이 지남에 따라 변화하는 환상이기 때문에 TimerxDelta을 사용합니다.

    은 당신의 코드 예제 내가 paintComponent`it 작동하지 않는`사용하는 몇 가지 이유 만`paint`를 들어

    import java.awt.BorderLayout; 
    import java.awt.Color; 
    import java.awt.Dimension; 
    import java.awt.EventQueue; 
    import java.awt.Graphics; 
    import java.awt.Graphics2D; 
    import java.awt.Rectangle; 
    import java.awt.event.ActionEvent; 
    import java.awt.event.ActionListener; 
    import java.util.Random; 
    import javax.swing.JFrame; 
    import javax.swing.JPanel; 
    import javax.swing.Timer; 
    import javax.swing.UIManager; 
    import javax.swing.UnsupportedLookAndFeelException; 
    
    public class Move { 
    
        public static void main(String[] args) { 
         new Move(); 
        } 
    
        public Move() { 
         EventQueue.invokeLater(new Runnable() { 
          @Override 
          public void run() { 
           try { 
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
           } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
           } 
    
           JFrame frame = new JFrame("Testing"); 
           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
           frame.setLayout(new BorderLayout()); 
           frame.add(new Main()); 
           frame.pack(); 
           frame.setLocationRelativeTo(null); 
           frame.setVisible(true); 
          } 
         }); 
        } 
    
        public static class Main extends JPanel { 
    
         public static int place = -350; 
         public Rectangle rect; 
         public int xDelta; 
    
         public Main() { 
    
          rect = new Rectangle(0, 75, 50, 50); 
          xDelta = 4; 
          Timer timer = new Timer(40, new ActionListener() { 
           @Override 
           public void actionPerformed(ActionEvent e) { 
            rect.x += xDelta; 
            if (rect.x + rect.width > getWidth() - 1) { 
             rect.x = getWidth() - rect.width; 
             xDelta *= -1; 
            } else if (rect.x < 0) { 
             rect.x = 0; 
             xDelta *= -1; 
            } 
            repaint(); 
           } 
          }); 
          timer.start(); 
    
         } 
    
         @Override 
         public Dimension getPreferredSize() { 
          return new Dimension(200, 200); 
         } 
    
         @Override 
         protected void paintComponent(Graphics g) { 
          super.paintComponent(g); 
          Graphics2D g2d = (Graphics2D) g.create(); 
          Random r = new Random(); 
          int r1; 
    
          r1 = r.nextInt(5); 
          if (r1 == 0) { 
           g2d.setColor(Color.WHITE); 
          } else if (r1 == 1) { 
           g2d.setColor(Color.BLUE); 
          } else if (r1 == 2) { 
           g2d.setColor(Color.RED); 
          } else if (r1 == 3) { 
           g2d.setColor(Color.GREEN); 
          } else if (r1 == 4) { 
           g2d.setColor(Color.PINK); 
          } else { 
           g2d.setColor(Color.CYAN); 
          } 
    
    //   place += 50; 
    
    //   rect = new Rectangle(place, 100, 300, 200); 
          g2d.draw(rect); 
          g2d.fill(rect); 
          g2d.dispose(); 
    
         } 
        } 
    } 
    
  • +0

    를 기반으로 업데이트되었습니다. '페인트 '를 사용하는 것은 나쁜 일입니다. –

    +0

    if 문에서 사각형을 뒤로 이동시키기 위해 실제로 무엇을 넣어야합니까? –

    +0

    @DilanHanrahan 최상위 컨테이너에는'paintComponent' 메소드가 없기 때문입니다. 최상위 컨테이너도 이중 버퍼링되지 않습니다. 또한 예제를 보았습니까? – MadProgrammer

    관련 문제