2012-12-05 41 views
1

我需要顯示棋盤。我有一個BoardPanel類,它擴展了包含BoardPanel的JPanel和GamePanel(也擴展了JPanel)類。 GamePanel填充所有的應用程序框架。如何以動態大小居中JPanel

我希望BoardPanel始終是一個大小等於GamePanel寬度和高度最小值的正方形(如果GamePanel的寬度大於高度,那麼左右兩邊應該有空白區域,如果它較小,則應該有空白區域在頂部和底部)。 BoardPanel應顯示在父面板的中心也很重要。

我寫了某事像這樣:

public GamePanel() { 
    setLayout(new BorderLayout(0, 0)); 
    boardPanel = new BoardPanel(...); 
    this.add(boardPanel, BorderLayout.CENTER); 
    ... 
} 

和BoardPanel:

public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    int size = Math.min(this.getParent().getHeight(), this.getParent().getWidth()); 
    this.setSize(size, size); 
    ... 
} 

它會調整好,但棋盤總是在的GamePanel的左上角顯示(顯示所有的空白處在機器人或權利),我不知道如何解決它。

任何幫助?提前致謝!

回答

4

中心。

Centered, square panel

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

public class CenteredPanel { 

    public static void main(String[] args) { 
     Runnable r = new Runnable() { 
      @Override 
      public void run() { 
       JPanel gui = new JPanel(new GridBagLayout()); 
       JPanel square = new SquarePanel(); 
       square.setBackground(Color.RED); 
       gui.add(square); 

       JFrame f = new JFrame("SquareBoard"); 
       f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
       f.setLocationByPlatform(true); 
       f.add(gui); 
       f.setMinimumSize(new Dimension(400,100)); 
       f.pack(); 
       f.setVisible(true); 
      } 
     }; 
     SwingUtilities.invokeLater(r); 
    } 
} 

class SquarePanel extends JPanel { 
    @Override 
    public Dimension getPreferredSize() { 
     Container c = this.getParent(); 
     int size = Math.min(c.getHeight(), c.getWidth()); 
     Dimension d = new Dimension(size,size); 
     return d; 
    } 
} 
+0

1非常好的例子 –

+2

@DavidKroukamp關於優選尺寸非常好的建議。當我注意到你在55分鐘前說過這個消息時,我「正要說出同樣的話」。 :) –

+0

非常感謝。我完美的工作。 – aerion

2
  • 無需new BorderLayout(0,0)簡單地使用默認構造BorderLayout

  • 不要調用setSize()而重寫的JPanelgetPreferredSize()像這樣:

    @Override 
    public void getPreferredSize() { 
    
         int size = Math.min(this.getParent().getHeight(), this.getParent().getWidth()); 
    
         return new Dimension(size,size); 
    } 
    
  • 也是它從來沒有好做的工作在你的因爲這應該只用於繪畫而已。

如果上述方法不工作,我會建議一個SSCCE說明具體問題,你可能有它使用GridBagLayout