在GridBagLayout中制作卷轴

时间:2014-04-08 12:28:22

标签: java swing user-interface layout jscrollpane

一天中的好时光,我正在尝试将卷轴添加到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是不正确的,当然它失败了。问题是:在这种情况下如何正确添加它们?我想要实现的目标是,如果超过游戏窗口大小,可以在游戏中滚动(移动)地图。 在此先感谢:)

1 个答案:

答案 0 :(得分:2)

我想问题是你尝试将GridBagConstraints添加到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);