无法在JDialog中设置JPanel的大小

时间:2014-05-04 21:14:01

标签: java swing jpanel layout-manager jdialog

我正在尝试创建Atari GO的小游戏,我的界面有问题。我有一个名为GameBoard的类,它扩展了JPanel类。在main方法中,我创建了这样的GameBoard,然后我创建了一个JDialog,将GameBoard添加到它,并在JDialog对象上调用pack()方法。而不是这个:My expected output

我明白了: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组件上使用不同的布局管理器,但没有结果。我该怎么做才能获得我想要的输出?谢谢。

2 个答案:

答案 0 :(得分:4)

覆盖类getPreferredSize()中的方法GameBoard,如下所示:

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

然后移除this.setSize(boardSize, boardSize);

答案 1 :(得分:4)

覆盖面板getPreferredSize方法并返回您想要的首选大小。

调用时,pack会向布局管理器询问内容窗格的首选大小,并确保可视区域尽可能满足这些要求

Ps:不要忘记从Graphics

处理BufferedImage上下文