在 GridBagLayout 中制作滚动



一天中的好时光,我正在尝试向GridBagLayout添加卷轴,但肯定错过了正确的方法。

代码:

public GUI(Map map)
{
    //declare image icons and try to read them
    ImageIcon missing = new ImageIcon();
    ImageIcon wall = new ImageIcon();
    ImageIcon floor = new ImageIcon();
    //set texture for missing cases
    try
    {
        Image tempImage = ImageIO.read(this.getClass().getResource("/resources/images/missing.png"));
        missing = new ImageIcon(tempImage.getScaledInstance(16, 16, Image.SCALE_DEFAULT));
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    try
    {
        Image tempImage = ImageIO.read(this.getClass().getResource("/resources/images/wall.png"));
        wall = new ImageIcon(tempImage.getScaledInstance(16, 16, Image.SCALE_DEFAULT));
        tempImage = ImageIO.read(this.getClass().getResource("/resources/images/floor.png"));
        floor = new ImageIcon(tempImage.getScaledInstance(16, 16, Image.SCALE_DEFAULT));
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    Container pane = getContentPane();
    pane.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();
    for (int i=0;i<map.getMapSize();i++)
    {
        for (int j=0;j<map.getMapSize();j++)
        {
            c.gridy=i;
            c.gridx=j;
            if (i==0 && j==0)
            {
                c.weightx=1;
                c.weighty=1;
            }
            else
            {
                c.weightx=0;
                c.weighty=0;
            }
            c.gridwidth=1;
            c.gridheight=1;
            c.fill = GridBagConstraints.BOTH;
            JLabel tile = new JLabel(missing);
            if (map.getElementAt(i, j)==0)
            {
                tile.setIcon(wall);
            }
            else
            {
                tile.setIcon(floor);
            }
            pane.add(tile, c);
        }
    }
    //c.gridx=map.getMapSize();
    JScrollPane thePane = new JScrollPane();
    pane.add(thePane, c);
    setTitle("Game GUI");
    setSize(640, 480);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}

据我了解,在填充窗格后添加JScrollPane是不正确的,当然也会失败。问题是:在这种情况下如何正确添加它们?我试图实现的总体目标是,如果地图超过游戏窗口大小,就能够在游戏中滚动(移动)地图。提前感谢:)

我想问题是你尝试将 GridBagConstraint 添加到 JScollPane 而不是添加你的 JPanel....

JScrollPane thePane = new JScrollPane();
pane.add(thePane, c);

试试这个:

JPanel myMapPanel = new Jpanel();
myMapPanel.setLayout(new GridBagLayout());
// add all the stuff to myMapPanel here (do the looping stuff here)
JScrollPane thePane = new JScrollPane(myMapPanel);
pane.add(thePane, c);

注意这一点:

new JScrollPane(myMapPanel);

相关内容

  • 没有找到相关文章

最新更新