gpt4 book ai didi

JAVA JPanel同时滑出和滑入

转载 作者:太空宇宙 更新时间:2023-11-04 13:02:10 29 4
gpt4 key购买 nike

我在移动 JPanel 时遇到问题。

我有一个 400x600 的窗口和一个 100x100 的 JPanel(红色)

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 滑出窗口到右侧,当它超出窗口宽度时,它开始从 -100 返回,所以从左侧

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

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

任何其他解决这个问题的技巧都值得赞赏。

最佳答案

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

所有这一切的关键是,在 TimerActionListener 中,我只需 getLocation() 每个tiles[i],将 5 添加到 x 坐标,并在达到 300 时将其重置为 -120,然后再次 setLocation(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);
}
}
}
}

关于JAVA JPanel同时滑出和滑入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34837689/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com