2013-12-16 23 views
1

因此,我正在爲一個類的多人Pong遊戲工作,並且當我試圖製作JButton然後調整窗口大小時,我會遇到這個奇怪的問題。JButton在調整大小時以奇怪的方式複製自己

縮短代碼:

private void init(String title) { 
    JFrame frame = new JFrame(title); 
    frame.setMinimumSize(new Dimension(480, 480)); 
    frame.setSize(600, 600); 
    frame.add(this); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 
    frame.setFocusable(true); 
    this.setFocusable(true); 
    this.setBackground(Color.WHITE); 
    Timer timer = new Timer(36, new TimeAction()); 
    timer.start(); 
    frame.addKeyListener(this); 
} 

public void addRestartButton() { 
    JButton btnRestartGame = new JButton("Restart Game"); 

    btnRestartGame.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent arg0) { 
      pong.initServer(); 
      pong.nowReady(); 
      w.setVisible(false); 
     } 
    }); 
    btnRestartGame.setBounds(getWidth()/2 - 100, getHeight() * 3/4, 200, 25); 
    add(btnRestartGame); 
} 
public void paintComponent(java.awt.Graphics g) { 
    super.paintComponent(g); 
    Image bufferImage = createImage(this.getSize().width, this.getSize().height); 
    Graphics2D bufferGraphics = (Graphics2D) bufferImage.getGraphics(); 

    bufferGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 
    g2 = (Graphics2D) bufferGraphics; 
    paintPolygon(); 
    paintBall(); 
    for (int i = 0; i < Pong.getPolygon().npoints; i++) 
     paintSide(Pong.getPolygon().getSide(i)); 
    g2.setTransform(unrotate); 
    paintScoreField(); 
    if (!pong.getScore().isPlaying()) { 
     paintWinnerName(pong.getScore().getWinner()); 
     if (comm instanceof Server) 
      addRestartButton(); 
    } 

    g.drawImage(bufferImage, 0, 0, this); 
} 

有關問題的圖片: http://imgur.com/a/rHxOa

有誰知道爲什麼發生這種情況,我該如何解決?

回答

3

在你paintComponent方法去除這些線路都

// if (comm instanceof Server) 
// addRestartButton(); 
+0

+1是,繪畫方法僅供因爲每當鞦韆確定了組件需要重新繪製這些方法被調用畫。你不應該在這個方法中創建一個組件。 – camickr

+0

這些代碼位於代碼的一部分,我檢查遊戲是否已結束。是的,從技術上講,它確實解決了我的問題,但它也完全消除了按鈕。 – KuroMajutsu

+0

@KuroMajutsu你沒有檢查遊戲是否先結束。你只是不斷添加按鈕。 –

相關問題