2013-04-08 2 views
-2

저는 Java 2D 그래픽에서 초보자입니다. 그리고 뭔가 잘못하면 저를 용서해주세요. 나는 현재 체인 반응을 포함하는 미니 게임을하려고 노력 중이다. 예를 들어 JPanel에 개별 스레드가있는 10 개의 공을 튀기고 싶습니다. JPanel에서 볼을 클릭하면 펼쳐지기를 원합니다. 단일 Java 파일 내에서이 작업을 처리했지만 별도의 파일로 작업 할 수 없습니다. 모든 입력을 부탁드립니다. 고맙습니다. 이들은 3 개 클래스가 일을하려고 메신저입니다Java 체인 반응 게임

import javax.swing.*; 
import java.awt.*; 
import java.awt.geom.*; 
import java.awt.event.*; 
import java.util.*; 

public class BounceBall extends JFrame { 

    private ShapePanel drawPanel; 
    private Vector<NewBall> Balls; 
    private JTextField message; 

    // set up interface 
    public BounceBall() { 
     super("MultiThreading"); 
     drawPanel = new ShapePanel(400, 345); 
     message = new JTextField(); 
     message.setEditable(false); 

     Balls = new Vector<NewBall>(); 
     add(drawPanel, BorderLayout.NORTH); 
     add(message, BorderLayout.SOUTH); 

     setSize(400, 400); 
     setVisible(true); 
     createBalls(); 
    } // end Ex20 constructor 

    public void createBalls() { 
     for (int i = 1; i <= 20; i++) { 
      NewBall nextBall = new NewBall(); 
      Balls.addElement(nextBall); 
      nextBall.start(); 
      message.setText("Number of Balls: " + Balls.size()); 
     } 
    } 

    public static void main(String args[]) { 

     BounceBall application = new BounceBall(); 

     application.addWindowListener(
      new WindowAdapter() { 
      public void windowClosing(WindowEvent e) { 
       System.exit(0); 
      } 
     }); 
    } 

    // Class NewBall is used to create a ball and move its position 
    // A thread overrides the run method to define how the ball behaves 
    // Each ball is one instance of this class 
    private class NewBall extends Thread { 

     private Ellipse2D.Double thisBall; 
     private boolean ballStarted, growBall, growEnd; 
     private int size = 30, speed = 70;    // characteristics 
     private int deltax, deltay;   // of the ball 
     Random r = new Random(); 
     int red = r.nextInt(255), green = r.nextInt(255), blue = r.nextInt(255); 

     public NewBall() { 
      // Create new ball with random size, speed, start point, 
      // and direction. "Speed" is actually the amount of sleep 
      // between moves. 
      ballStarted = true; 
      // size = 10 + (int)(Math.random() * 60); 
      // speed = 10 + (int)(Math.random() * 100); 
      int startx = (int) (Math.random() * 300); 
      int starty = (int) (Math.random() * 300); 
      deltax = -10 + (int) (Math.random() * 21); 
      deltay = -10 + (int) (Math.random() * 21); 
      if ((deltax == 0) && (deltay == 0)) { 
       deltax = 1; 
      } 
      thisBall = new Ellipse2D.Double(startx, starty, size, size); 
     } 

     public void draw(Graphics2D g2d) { 
      if (thisBall != null) { 
       g2d.setColor(new Color(red, green, blue, 80)); 
       g2d.fill(thisBall); 
      } 
     } 

     public void grow() { 
      growBall = true; 
     } 

     void removeBall() { 
      for (int i = 0; i < Balls.size(); i++) { 
       Balls.remove(i); 
      } 

      repaint(); 
     } 

     public double getPositionX() { 
      return thisBall.getX(); 
     } 

     public double getPositionY() { 
      return thisBall.getY(); 
     } 

     public int radius() { 
      return size * 2; 
     } 

     public void run() { 
      while (ballStarted && !growBall) // Keeps ball moving 
      { 
       try { 
        // To free up processor time 
        Thread.sleep(speed); 

       } catch (InterruptedException e) { 
        System.out.println("Woke up prematurely"); 
       } 

       // calculate new position and move ball 
       int oldx = (int) thisBall.getX(); 
       int oldy = (int) thisBall.getY(); 
       int newx = oldx + deltax; 
       if (newx + size > drawPanel.getWidth() || newx < 0) { 
        deltax = -deltax; 
       } 
       int newy = oldy + deltay; 
       if (newy + size > drawPanel.getHeight() || newy < 0) { 
        deltay = -deltay; 
       } 
       thisBall.setFrame(newx, newy, size, size); 

       while (growBall && size < 80) { 
        try { 
         // To free up processor time 
         Thread.sleep(speed); 

        } catch (InterruptedException e) { 
         System.out.println("Woke up prematurely"); 
        } 
        size++; 
        thisBall.setFrame(newx, newy, size, size); 

        for (int i = 0; i < Balls.size(); i++) { 
         if (thisBall.contains(Balls.get(i).thisBall.x, Balls.get(i).thisBall.y)) { 
          Balls.get(i).grow(); 
         } 
        } 
       } 
       drawPanel.repaint(); 
      } 
     } 
    } // end NewBall 

    // Define a class to be a panel on which the balls are drawn 
    private class ShapePanel extends JPanel { 

     private int prefwid, prefht; 

     public ShapePanel(int pwid, int pht) { 
      prefwid = pwid; 
      prefht = pht; 


      // add ball when mouse is clicked 
      addMouseListener(
       new MouseAdapter() { 
       public void mousePressed(MouseEvent e) { 
        stopBall(e); 

       } 
      }); 
     } 

     public void stopBall(MouseEvent e) { 
      for (int i = 0; i < Balls.size(); i++) { 
       if (Balls.get(i).thisBall.contains(e.getPoint())) { 
        Balls.get(i).grow(); 
       } 
      } 
     } 

     public Dimension getPreferredSize() { 
      return new Dimension(prefwid, prefht); 
     } 

     public void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Graphics2D g2d = (Graphics2D) g; 
      for (int i = 0; i < Balls.size(); i++) { 
       (Balls.elementAt(i)).draw(g2d); 
      } 
     } 
    } // end ShapePanel inner class 
} // end BounceBall 

:

이 내 하나의 파일 BounceBall.java입니다 Ball.java을

import java.awt.Color; 
import java.awt.Graphics2D; 
import java.awt.geom.Ellipse2D; 
import java.util.Random; 


public class Ball extends Thread { 
    public Ellipse2D.Double thisBall; 
    public int size=30,xPoz,yPoz; 
    Random r=new Random(); 
    int red=r.nextInt(255),green=r.nextInt(255),blue=r.nextInt(255); 
    int deltax,deltay; 
    public boolean ballStarted; 

    public Ball() 
    {xPoz=(int)Math.random(); 
    yPoz=(int)Math.random(); 
    ballStarted = true; 
    deltax=-10+(int)(Math.random()*21); 
    deltay=-10+(int)(Math.random()*21); 
    if ((deltax == 0) && (deltay == 0)) { deltax = 1; } 
    thisBall=new Ellipse2D.Double(xPoz,yPoz,size,size); 
    super.start(); 
    } 

    public void draw(Graphics2D g2d){ 
    if(thisBall!=null) 
    {g2d.setColor(new Color(red,green,blue,80)); 
    g2d.fill(thisBall); 
    } 
    } 

    public int PozX(){return xPoz;} 
    public int PozY(){return yPoz;} 
    public int radius(){return size*2;} 

    public void grow(){ 
    size++; 
    thisBall.setFrame(xPoz,yPoz,size,size); 
    } 

    public void move(){ 
     int oldx=xPoz; 
     int oldy=yPoz; 

     int newx=oldx+deltax; 
     int newy=oldy+deltay; 

     if(newx+size>800 || newx<0) 
      deltax=-deltax; 
     if(newy+size>600 || newy<0) 
      deltay=-deltay; 

     thisBall.setFrame(newx,newy,size,size); 
    } 

    public void run(){ 
     try { 

       Thread.sleep(100); 

      } 
      catch (InterruptedException e) 
      { System.out.println("Thread Halted");} 
     while(ballStarted) 
     {move();} 

    } 

} 

ShapePanel.java :

public class ShapePanel extends JPanel{ 
    private int prefwid, prefht,nrBalls; 
    public Vector<Ball> Balls=new Vector<Ball>();; 

     public ShapePanel (int pwid, int pht) 
     { 
     prefwid = pwid; 
     prefht = pht; 



     addMouseListener(

     new MouseAdapter() { 
      public void mousePressed(MouseEvent e) 
        { 


        } 
       } 
     ); 
     } 

    public void createBalls(){ 
    for(int i=1;i<=nrBalls;i++) 
    { Ball movingBall=new Ball(); 
     Balls.addElement(movingBall); 
     //movingBall.start(); 

    } 

    } 


     public Dimension getPreferredSize() 
     { 
     return new Dimension(prefwid, prefht); 
     } 

     public void setNrBalls(int n){this.nrBalls=n;} 

     public void paintComponent (Graphics g) 
     { 
      super.paintComponent(g); 
      Graphics2D g2d = (Graphics2D) g.create(); 
      g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
      for (Ball ball : Balls) { 
       ball.draw(g2d); 
      } 
      g2d.dispose(); 
     } 
    } 

그리고 BallBlaster.java :

import java.awt.BorderLayout; 
import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import java.awt.event.WindowAdapter; 
import java.awt.event.WindowEvent; 
import java.util.Vector; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.JTextField; 


public class BallBlaster extends JFrame 
{ 
    private ShapePanel drawPanel; 

    private JTextField message; 

    // set up interface 
    public BallBlaster() 
    { 
     super("MultiThreading"); 
     drawPanel = new ShapePanel(800, 600); 
     message = new JTextField("Number of balls : "); 
     message.setEditable(false); 


     add(drawPanel, BorderLayout.NORTH); 
     add(message, BorderLayout.SOUTH); 

     setSize(800, 600); 
     setVisible(true); 

     drawPanel.setNrBalls(20); 
     drawPanel.repaint(); 
    } 


    public static void main(String args[]) { 

     BoomShine application = new BoomShine(); 

     application.addWindowListener(
     new WindowAdapter() 
     { 
      public void windowClosing(WindowEvent e) 
      { 
       System.exit(0); 
      } 
     } 
    ); 
    } 

} 
+6

무엇이 질문입니까? 또한 많은 코드가 있습니다. 단축 된 [SCCE] (http://sscce.org/) 버전 – Reimeus

+0

게시 관련 코드 부분 만 게시하십시오. –

+0

죄송합니다. 귀하의 모든 코드를 덤핑해도 [sscce] (http://sscce.org/)에 대한 해결책 –

답변

1

내부 클래스를 public 클래스로 변환 할 때 객체 참조를 적절한 클래스로 옮겨야합니다. 예를 들어 Balls 배열은 ShapePanel에 있어야하며 Ball 클래스는 ShapePanel에 대한 참조를 가져야합니다. 공을 만들고 제거하는 방법은 ShapePanel로 이동해야합니다. 그렇게하면 각 클래스에 단일 반응성을 부여하는 ShapePanel은 공, 공 이동 등으로 작동합니다.

+0

@ user2257714 : IDE에서 내부 클래스를 정적으로 만들면 영향을받는 참조를 식별하는 데 도움이됩니다. 초기화 순서 문제를 해결해야합니다. – trashgod