我想創建一個Atari GO的小遊戲,並且我遇到了接口問題。我有一個名爲GameBoard
的課程,它擴展了JPanel
課程。在主要方法中,我創建了GameBoard
,然後我創建一個JDialog
,將GameBoard
添加到它,然後調用JDialog
對象上的pack()方法。相反得到這個的:無法設置JDialog中JPanel的大小
我得到這個:
這裏是我的代碼:
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的組件上使用不同的佈局管理器嘗試過,但沒有結果。我應該怎麼做才能得到我想要的輸出?謝謝。
@zan不用擔心 – MadProgrammer