2014-05-04 77 views
1

我想創建一個Atari GO的小遊戲,並且我遇到了接口問題。我有一個名爲GameBoard的課程,它擴展了JPanel課程。在主要方法中,我創建了GameBoard,然後我創建一個JDialog,將GameBoard添加到它,然後調用JDialog對象上的pack()方法。相反得到這個的:My expected output無法設置JDialog中JPanel的大小

我得到這個:What i get

這裏是我的代碼:

package view; 

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.FlowLayout; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.RenderingHints; 
import java.awt.image.BufferedImage; 

import javax.swing.BorderFactory; 
import javax.swing.JDialog; 
import javax.swing.JPanel; 
import javax.swing.border.BevelBorder; 

public class GameBoard extends JPanel{ 
    BufferedImage backgroundImage; 
    int boardSize; 
    public GameBoard(){ 
     super(); 
    } 
    public void initUi(){ 
     this.setBackground(Color.white); 
    } 
    public boolean setBoardSize(int nr) { 
     //setting the dimension of the board 
     this.boardSize = nr * 30; 
     this.setSize(boardSize, boardSize); 
     //i do some drawing next on a BufferedImage 
     backgroundImage = new BufferedImage(this.boardSize, this.boardSize, BufferedImage.TYPE_INT_RGB); 
     Graphics2D g2 = (Graphics2D)backgroundImage.getGraphics(); 
     g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 

     g2.setColor(new Color(153,102,51)); 
     g2.fillRect(0, 0,this.boardSize, this.boardSize); 

     g2.setColor(new Color(255,255,51)); 
     for (int i = 0; i < nr; i++) { 
      g2.drawLine(0, 15 + i * 30, this.boardSize, 15 + i * 30); 
      g2.drawLine(15 + i * 30, 0, 15 + i * 30, this.boardSize); 

     } 

     g2.setColor(new Color(255,51,102)); 
     g2.drawRect(2, 2, this.boardSize-4, this.boardSize-4); 

     return true; 
    } 
    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     Graphics2D g2 = (Graphics2D)g; 
     g2.drawImage(backgroundImage, 0, 0, null); 
    } 
    public static void main(String []args){ 
     //i create here a GameBoard 
     GameBoard board = new GameBoard(); 
     board.initUi(); 
     board.setBoardSize(10); 

     JDialog gameDialog = new JDialog(); 
     gameDialog.setLocationRelativeTo(null); 
     gameDialog.setModal(true); 
     gameDialog.add(board); 
     gameDialog.pack(); 
     gameDialog.setVisible(true); 
    } 

} 

我的JDialog的組件上使用不同的佈局管理器嘗試過,但沒有結果。我應該怎麼做才能得到我想要的輸出?謝謝。

回答

4

覆蓋面板getPreferredSize方法並返回所需的首選大小。

調用時,pack會問佈局管理器的內容窗格中的首選大小,並確保可視區域,儘可能多地能,滿足這些要求

PS:不要忘了處理的Graphics上下文來自BufferedImage

+0

@zan不用擔心 – MadProgrammer

4

覆蓋的方法getPreferredSize()GameBoard類是這樣的:

@Override 
public Dimension getPreferredSize() { 
    return new Dimension(boardSize, boardSize); 
} 

,並清除this.setSize(boardSize, boardSize);