将JPanel放在JScroll窗格中以保存2D平铺贴图

时间:2015-05-04 00:07:20

标签: java swing dictionary 2d jscrollpane

我有一个100 x 100的2D Tile数组地图。我可以将地图绘制出来并添加到JFrame中,但框架非常大,地图不适合框架。我希望在一个窗口中显示地图,当您移动鼠标时,框架会移动,您会看到更多的地图。所以我试图将一个JPanel添加到JScrollPane来实现这一目标。 Panel会有整个地图,JScrollPane会显示它的一部分,并在你移动时改变。但是我不知道如何将我的地图图像添加到JPanel,也不知道如何将ScrollPane添加到Frame。或者,如果我甚至正确设置ScrollPane。现在,当我尝试设置尺寸时,我得到一个空指针异常。在我的课堂上,我试图测试所有绘图内容。

package view;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Observable;
import java.util.Observer;
import java.util.Timer;
import java.util.TimerTask;

import model.*;

import javax.swing.*;
public class DrawMap extends JPanel implements Observer{
    private static  Map map = Map.getMap(); 
    private static Tile[][] field = map.getField();
    private BufferedImage img = map.getMapImage();
    private JScrollPane wrapper;
    private JPanel panel;
    /**
     * Test for drawing the Map
     */
    public DrawMap() {
        init();


    }
    public void init(){
        map.getMapImage();
        panel = new JPanel();
        for(int i = 0; i < 100; i ++){
            for(int j = 0; j < 100; j++){
                field[i][j].addObserver(this);
            }
        }
        panel.setSize(new Dimension(32 * 100, 32 * 100));
        panel.setPreferredSize(new Dimension(32 * 100, 32 * 100));

        wrapper.setSize(new Dimension(600, 400));
        wrapper.setPreferredSize(new Dimension(600, 400));
        wrapper.setViewportView(new JViewport().add(panel));
        this.add(wrapper);
    }
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(img,0,0,null);

    }

    public static void main(String[] args){
        JFrame frame = new JFrame("GameMap");
        DrawMap draw = new DrawMap();
        frame.add(draw);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(3200,3200);
        frame.setVisible(true);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        field[1][1].setAgent();
    }
    @Override
    public void update(Observable o, Object arg) {
        System.out.println("About to update tile");
        Graphics2D g = (Graphics2D) img.getGraphics();
        ((Tile) arg).drawTile(g, ((Tile) arg).getXChord() * 32, ((Tile) arg).getYChord() * 32);
        //map.drawMap();
        //img = map.getMapImage();
        repaint();
        System.out.println("Tile was changed");

    }

}

任何帮助将不胜感激,谢谢!

0 个答案:

没有答案