0

我最近一直在玩java,我正在尝试开发一个小游戏。问题是,我使用的 JViewport 没有更新。当在 Viewport 上调用 repaint 方法时,Viewport 在正确的位置闪烁,并且 Viewport 显示的整个图像都在背景中绘制并且运行正常。我如何只绘制视口,而不是整个其余部分?谢谢回复;

    public start() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Dimension my = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        Rectangle myrec = new Rectangle(0,0,my.width, my.height);
        setBounds(myrec);
        this.setUndecorated(true);

        JPanel Background = new JPanel();
        Background.setBounds(myrec);
        Background.setLayout(null);
        setContentPane(Background);

        JScrollPane map = new JScrollPane();
        map.setBounds(0, 0, 3000, 3000);
        map.setLayout(null);

        //setContentPane(map);

        gameoberflaeche MainMap = new gameoberflaeche();
        MainMap.setBounds(0,0, map.getWidth(), map.getHeight());
        MainMap.setup();
        map.add(MainMap);

        Viewport currview = new Viewport(myrec, MainMap.player_1, map);
        Background.add(currview);
        //setContentPane(currview);

        int delay = (1000/30);
        ActionListener update = new ActionListener(){
            public void actionPerformed(ActionEvent evt) { 
                MainMap.Anfang.checkdead();
                //currview.stats.update();
                //currview.weaponpanel.update();
                //currview.MagPanel.update();
                currview.update(MainMap.player_1.field.x, MainMap.player_1.field.y);

            }
        };
        new Timer(delay, update).start();

    }


        public class Viewport extends JViewport{
    Player myplayer;
    statpanel stats;
    Magazin MagPanel;
    Waffenpanel weaponpanel;
    Rectangle myrec;

    public Viewport(Rectangle myrec, Player myp, JScrollPane myview) {
        setView(myview);
        reshape(0,0,myrec.width,myrec.height);
    }

    public void update(int x, int y) {

    //  System.out.println(getView());
        setViewPosition(new Point(x,y));
        System.out.println(x + " " + y + " " + getViewRect());
    }

}
4

1 回答 1

1
JPanel Background = new JPanel();

变量名不应以大写字符开头。

Background.setLayout(null);

不要使用空布局。Swing 旨在与布局管理器一起使用。

JScrollPane map = new JScrollPane();
map.setLayout(null);

永远不要在 JScrollPane 上使用空布局。JScrollPane 使用内部布局管理器来管理水平/垂直滚动条、行/列标题和视口等。

Viewport currview = new Viewport(myrec, MainMap.player_1, map);

不要创建新的视口。要更新滚动窗格中的组件,您只需将组件添加到滚动窗格的视口:

scrollPane.getViewport().setView(...);
于 2017-11-30T01:16:48.553 回答