JAVA JPanel同时滑出和滑入

JAVA JPanel sliding out and sliding in at the same time

我在移动 JPanel 时遇到问题。

我有一个 window 400x600 和一个 JPanel(红色)100x100

public class RulettModel {
    private int num;

    public void Slide() {
        num = num + 1;
        if(num > 600) {
            num = -100;
        }
    }

    public int getNum() {
        return num;
    }
}

class RulettListener implements ActionListener{
    Timer tm = new Timer(1, this);

   @Override
    public void actionPerformed(ActionEvent e) {
        tm.start();
        int y = 0;

        theModel.Slide();

        theView.setNewLocationOfPiros(theModel.getNum(), y);         
    }
}

void setNewLocationOfJpanel(int x, int y) {
    JPanel1.setLocation(x,y);
 }

这段代码是我的代码的一部分,这里需要它,它工作正常我的 JPanel 从 window 滑出到右侧,当它超出 window 宽度时它开始出现从-100 回来所以从左边

我遇到的问题: 我希望我的 JPanel 在它从右侧完全退出之前从左侧进入。

因此,如果面板的一半已经熄灭,那么那一半应该已经出现在左侧,所以我的面板应该一次出现在 2 个位置,一半在这里,一半在那里,这有可能吗?

解决该问题的任何其他提示。

我猜您需要 2 个 JPanel。那我就

public class RulettModel {
    private int num1, num2;

    public void Slide() {
        num1 = num1 + 1;
        if(num1 > 600) {
            num2 = 500-num1;
        }
    }

    public int getNum1() {
        return num1;
    }

    public int getNum2() {
        return num2;
    }
}

并有 setNewLocOfJPanel1(int, int)setNewLocOfJPanel2(int, int) 方法

在编写下面的代码之前,我使用 Microsoft Paint 制作了 7 个不同颜色的矩形,宽 60 像素,高 90 像素。在你看到 jf.setSize(186,120) 的地方,我只是通过反复试验得到这些值。我只是猜测我的 timerDelay 是一个合适的值。所有其他值的原因应该很明显。

所有这一切的关键是,在 TimerActionListener 中,我只是简单地对每个图块 [i] 进行 getLocation(),将 5 添加到 x co-ordinate,并在达到 300 时将其重置为 -120,然后再次设置位置(int,int)。

package SlidingTiles;

import ...;

public class Main 
{
    private static int timerDelay = 100;
    private static Timer t = new Timer(timerDelay, new TimerActionListener());

    private static JFrame jf = new JFrame();
    private static JPanel jp = new JPanel();
    private static String[] colors = { "blue", "brown", "green", "grey", "purple", "red", "yellow" };
    private static JLabel[] tiles = new JLabel[7];

    public static void main(String[] args) 
    {


        for(int i=0; i<7; ++i)
        {
            tiles[i] = new JLabel(new ImageIcon("tiles/"+colors[i]+".jpg"));
            tiles[i].setBounds(-120+60*i,0,60,90);
            jf.add(tiles[i]);
        }

        jf.add(jp);
        jf.setSize(186,120);
        jf.setResizable(false);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        t.start();
    }

    public static class TimerActionListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e)
        {
            for(int i=0; i<7; ++i)
            {
                Point p = tiles[i].getLocation();
                int newX = (int) p.getX()+5;
                if(newX == 300)
                    newX = -120;

                tiles[i].setLocation(newX, 0);
            }
        }
    }
}