2016-11-23 71 views
0

我想將一個球添加到JPanel中,但是我不確定如何做到這一點以下是我現在將球添加到JPanel中的代碼。我試圖在屏幕上隨機添加多個球。第一個按預期方式出現,但不是出現在屏幕上。如何將一個對象添加到JPanel中

球類;

public class Ball extends Component { 

public static double ballX = rand.nextInt(500) + 40; 
public static double ballY = rand.nextInt(300) + 10; 
public static Ball[] balls = new Ball[20]; 

public Ball() { 

} 

public void draw(Graphics g2) {    
    Color color = new Color(r, g, b); 
    g2.setColor(color); 
    g2.fillOval((int) ballX, (int) ballY, 30, 30); 
} 
} 

嘗試將球添加到JPanel中的方法;

public class BallFrames extends JFrame { 

/* creates static varibles privite for use withing class and public for 
    use out side of the class */ 
public static final JPanel controlPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); 
public static final JPanel ballPanel = new JPanel(); 
public static JButton button; 
public static JPanel displayPanel = new JPanel(new BorderLayout()); 
private static int FRAME_WIDTH = 600; 
private static int FRAME_HEIGHT = 600; 

/** 
* constructor called method to create the components 
*/ 
public BallFrames() { 
    setSize(FRAME_WIDTH,FRAME_HEIGHT); 
    createComponents(); // creates all compononents 
} 

/* 
* calls helper methods to create all of the componanats needed 
*/ 
private void createComponents() { 
    ActionListener listener = new BallListener(); 
    createPanel(); // creates a panel 
    createButtons(listener); // Creates a button 
    createSlider(); 
} 

/** 
* method to create panels 
*/ 
public void createPanel() { 
    BallComponent component = new BallComponent(); // creates a new BallCompoenet 
    displayPanel.add(component, BorderLayout.CENTER); 
    displayPanel.add(controlPanel, BorderLayout.SOUTH); // adds thecontrol panel 
    add(displayPanel); // adds the dice to the JFrame 
} 

public static void addBall() throws InterruptedException { 
    Ball.balls[BallListener.balls] = new Ball(); 
    System.out.println(BallListener.balls); // testing 
    ballPanel.add(Ball.balls[BallListener.balls]); 
    // ballPanel.add(ball); 
    Runnable r = new BallRunnable(); 
    Thread t = new Thread(r); 
    t.start(); 
    t.join(); 
    ballPanel.repaint(); 
} 

我如何繪製它們;

public class BallComponent extends JComponent { 

/** 
* calls paintComponenet to render images on the screen 
* 
* @param g 
*/ 
@Override 
public void paintComponent(Graphics g) { 
    int delay = 1000; 
    super.paintComponent(g);  // call to super 
    Graphics2D g2 = (Graphics2D) g; // recover the graphic  

    TimerListener listener = new TimerListener(); 
    Timer t = new Timer(delay, listener);  

    if (BallListener.gameOn == true) { 
     for(int i = 0; i < BallListener.balls; i++){   
      Ball.balls[i].draw(g2); 
     } 

    BallFrames.displayPanel.repaint(); 
} 
} 

ActionListener for the buttons; 

public class BallListener implements ActionListener { 

public static boolean gameOn = false; 
public static int balls = 0; 

/** 
* gets the which button has been pressed and responds appriately 
* 
* @param event based on the event it will preform selected actions 
*/ 
@Override 
public void actionPerformed(ActionEvent event) { 
    String action = event.getActionCommand(); 

    switch (action) { 
     case "start": 
      gameOn = true; 

      { 
       try { 
        BallFrames.addBall(); 
       } catch (InterruptedException ex) { 
        Logger.getLogger(BallListener.class.getName()).log(Level.SEVERE, null, ex); 
       } 
       balls++; 
      } 
      BallFrames.displayPanel.repaint(); 
      break; 
     case "pause": 

      break; 
    } 
} 

Ball Runnable;

public class BallRunnable implements Runnable { 

private static Random rand = new Random(); 
public static boolean goLeft = true; 
public static boolean goRight = false; 
public static boolean goUp = false; 
public static boolean goDown = false; 
public static boolean diagonalUp = false; 
public static boolean diagonalDown = false; 
public static double speed = 0.2f; 

public BallRunnable() { 

} 

public void run() { 
    boundsCheckY1(); 
    boundsCheckX1(); 
    boundsCheckY2(); 
    boundsCheckX2(); 
} 

public void boundsCheckX1() { 
    int temp; 

    if (Ball.ballX < 1) { 
     temp = rand.nextInt(5) + 1; 

     if(temp == 1) { 
      goRight = true; 
      goLeft = false; 
      goUp = false; 
      goDown = false; 
      diagonalUp = false; 
      diagonalDown = false; 
     } else if (temp == 2) { 
      goRight = true; 
      goUp = true; 
      goDown = false; 
      goLeft = false; 
      diagonalUp = false; 
      diagonalDown = false; 
     } else if (temp == 3) { 
      goRight = true; 
      goUp = false; 
      goDown = true; 
      goLeft = false; 
      diagonalUp = false; 
      diagonalDown = false; 
     } else if (temp == 4) { 
      goRight = true; 
      goUp = false; 
      goDown = false; 
      goLeft = false; 
      diagonalUp = true; 
      diagonalDown = false; 
     } else if (temp == 5) { 
      goRight = true; 
      goUp = false; 
      goDown = false; 
      goLeft = false; 
      diagonalUp = false; 
      diagonalDown = true; 
     } 
    } 
} 

public void boundsCheckY1(){ 
    int temp; 

    if (Ball.ballY < 1) { 
     temp = rand.nextInt(5) + 1; 

     if(temp == 1) { 
      goRight = false; 
      goLeft = false; 
      goUp = false; 
      goDown = true; 
      diagonalUp = false; 
      diagonalDown = false; 
     } else if (temp == 2) { 
      goRight = false; 
      goUp = false; 
      goDown = true; 
      goLeft = true; 
      diagonalUp = false; 
      diagonalDown = false; 
     } else if (temp == 3) { 
      goRight = true; 
      goUp = false; 
      goDown = true; 
      goLeft = false; 
      diagonalUp = false; 
      diagonalDown = false; 
     } else if (temp == 4) { 
      goRight = true; 
      goUp = false; 
      goDown = true; 
      goLeft = false; 
      diagonalUp = false; 
      diagonalDown = true; 
     } else if (temp == 5) { 
      goRight = false; 
      goUp = false; 
      goDown = true; 
      goLeft = true; 
      diagonalUp = false; 
      diagonalDown = true; 
     } 
    } 
} 

public void boundsCheckX2() { 
    int temp; 

    if (Ball.ballX > 559) { 
     temp = rand.nextInt(5) + 1; 

     if(temp == 1) { 
      goRight = false; 
      goLeft = true; 
      goUp = false; 
      goDown = false; 
      diagonalUp = false; 
      diagonalDown = false; 
     } else if (temp == 2) { 
      goRight = false; 
      goUp = true; 
      goDown = false; 
      goLeft = true; 
      diagonalUp = false; 
      diagonalDown = false; 
     } else if (temp == 3) { 
      goRight = false; 
      goUp = false; 
      goDown = true; 
      goLeft = true; 
      diagonalUp = false; 
      diagonalDown = false; 
     } else if (temp == 4) { 
      goRight = false; 
      goUp = false; 
      goDown = false; 
      goLeft = true; 
      diagonalUp = true; 
      diagonalDown = false; 
     } else if (temp == 5) { 
      goRight = false; 
      goUp = false; 
      goDown = false; 
      goLeft = true; 
      diagonalUp = false; 
      diagonalDown = true; 
     } 
    } 
} 

public void boundsCheckY2() { 
    int temp; 

    if (Ball.ballY > 470) { 
     temp = rand.nextInt(5) + 1; 

     if(temp == 1) { 
      goRight = false; 
      goLeft = false; 
      goUp = true; 
      goDown = false; 
      diagonalUp = false; 
      diagonalDown = false; 
     } else if (temp == 2) { 
      goRight = false; 
      goUp = true; 
      goDown = false; 
      goLeft = true; 
      diagonalUp = false; 
      diagonalDown = false; 
     } else if (temp == 3) { 
      goRight = true; 
      goUp = true; 
      goDown = false; 
      goLeft = false; 
      diagonalUp = false; 
      diagonalDown = false; 
     } else if (temp == 4) { 
      goRight = true; 
      goUp = true; 
      goDown = false; 
      goLeft = false; 
      diagonalUp = true; 
      diagonalDown = false; 
     } else if (temp == 5) { 
      goRight = false; 
      goUp = true; 
      goDown = false; 
      goLeft = true; 
      diagonalUp = true; 
      diagonalDown = false; 
     } 
    } 
} 

}

觀察者類;

public class BallViewer { 

/** 
* creates the main frame 
* 
* @param args 
*/ 
public static void main(String[] args) throws InterruptedException { 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      try { 
       for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { 
        if ("Nimbus".equals(info.getName())) { 
         UIManager.setLookAndFeel(info.getClassName()); 
         break; 
        } 
       } 
      } catch (Exception e) { 
       // If Nimbus is not available, you can set the GUI to another look and feel. 
      } 
      // new BallFrames().setVisible(true); 
      JFrame frame = new BallFrames(); // creates new JFrame  
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      frame.setTitle("Multi-Treaded Balls");// Sets the Title  
      frame.setVisible(true); // Makes the frame visible 
      frame.setResizable(false); 
     } 
    }); 
} 

}

定時器偵聽器; 公共類TimerListener實現的ActionListener {

@Override 
public void actionPerformed(ActionEvent event) { 
    String action = event.getActionCommand(); 

    try { 
     movement(); 
    } catch (InterruptedException ex) { 
     Logger.getLogger(TimerListener.class.getName()).log(Level.SEVERE, null, ex); 
    } 

} 
public void movement() throws InterruptedException { 
    if(goLeft == true) {  
     Ball.ballX -= speed;      
    } 
    if(goRight == true) { 
     Ball.ballX += speed;   
    } 
    if(goUp == true) { 
     Ball.ballY -= speed;       
    } 
    if(goDown == true) { 
     Ball.ballY += speed;    
    } 
    if(diagonalUp == true) { 
     Ball.ballY += speed/2;    
    } 
    if(diagonalDown == true) { 
     Ball.ballY -= speed/2;   
    } 

} 

}

我希望能夠在給定的時間,這也移動周圍像第一個球加在屏幕上不止一個球。

+0

它確實延長元件,生病中的代碼添加。 – Ryan

+0

你得到的錯誤是什麼? – RealSkeptic

+0

對不起,這只是他們留下的舊評論,並不是一個錯誤,球似乎並沒有被添加到第一個之後的屏幕上。 – Ryan

回答

1

你的球類的定義,表現爲預期:

public class Ball extends Component { 

public static double ballX = rand.nextInt(500) + 40; 
public static double ballY = rand.nextInt(300) + 10; 
public static Ball[] balls = new Ball[20]; 

public Ball() { 

} 

public void draw(Graphics g2) {    
    Color color = new Color(r, g, b); 
    g2.setColor(color); 
    g2.fillOval((int) ballX, (int) ballY, 30, 30); 
} 
} 

所有static字段在類的所有實例之間共享。這就是static的意思。所有Ball s都有相同的座標ballXballY

您正在查找的是不屬於每個單獨實例的static字段。每當您製作新球時,您還必須初始化這些字段。當類加載時,static字段只會初始化一次。還有一些我會推薦的更改:

  • 如果您的x和y座標只屬於一個球,最好使它們爲private
  • 擴展JComponent而不是Component,因爲你明明在這裏使用swing。
  • 執行paintComponent而不是draw。如果沒有其他的話,它會使你的繪圖代碼需要更少的維護。

下面是類的版本,應該工作好一點:

public class Ball extends JComponent 
{ 

    private double ballX; 
    private double ballY; 
    public static Ball[] balls = new Ball[20]; 

    public Ball() 
    { 
     ballX = rand.nextInt(500) + 40; 
     ballY = rand.nextInt(300) + 10; 
    } 

    public void paintComponent(Graphics g2) 
    { 
     Color color = new Color(r, g, b); 
     g2.setColor(color); 
     g2.fillOval((int) ballX, (int) ballY, 30, 30); 
    } 
} 
0

繪畫代碼僅用於繪畫。

您不應該在繪畫方法中創建/啓動計時器。擺脫所有的代碼。

你永遠不應該調用repaint(),這會導致無限循環。

另外,擺脫你所有的動畫代碼。你的第一個任務是在面板上畫多個球。一旦你得到這個工作,那麼你擔心試圖做動畫。

由於您的類不是組件,因此無需擴展JComponent。這是你永遠不會將組件添加到面板。你所做的就是在另一個班上畫對象。

所以你的BallComponent類(它是一個組件)需要有一個ArrayList跟蹤你想要繪製的球對象。所以你需要一個方法來向這個ArrayList添加一個球對象。然後paintComponent()方法只是遍歷列表並繪製所有球。

查看Custom Painting Approaches中的DrawOnComponent示例。

+0

感謝您對camickr的反饋我已經看過您的示例,並且同意您所說的我正在從您發佈的示例中尋找和學習。 – Ryan

相關問題