gpt4 book ai didi

Java timer&paint组件问题

转载 作者:行者123 更新时间:2023-11-30 09:35:17 24 4
gpt4 key购买 nike

您好,我正在尝试让一个红色框出现在 JPanel 的底部。我希望这个框移动到屏幕的一个角落并停止,然后开始向另一边移动,但是我一直无法做到box stop 以下是我一直在使用的代码

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;

public class JavaApplication13 extends JPanel {

public static void main(String[] args) {
JFrame rough = new JFrame("Panamr");
rough.setVisible(true);
rough.setLocation(1, 1);
rough.setSize(500, 500);
rough.setContentPane(mamals);
}

public static int iomega(int x, int y) {
if (y == 1) {
diget = -5;
time.stop();
}
if (y == 0) {
diget = 5;
}
return diget;
}
static JavaApplication13 mamals = new JavaApplication13();

JavaApplication13() {
setBackground(Color.red);
}
static int oy = 400;
static int ox = 200;
static int diget;
static Timer time = new Timer(100, new ActionListener() {

public int xy = 1;

@Override
public void actionPerformed(ActionEvent e) {
iomega(ox, xy);
if (ox == 500) {
xy = 1;
}
if (ox == 0) {
xy = 0;
}
ox = ox - iomega(ox, oy);
/*if(ox!=500){
ox=ox-diget;
if(ox==0){
diget=-5;}
else {
diget=5;
}
}*/
}
});
boolean test = true;

public void paint(Graphics g) {
super.paint(g);
g.setColor(Color.black);
g.fillRect(ox, oy, 60, 60);
time.start();
repaint();
}
}

最佳答案

您的框架/面板尺寸坐标已关闭,您可能应该动态计算,或者有一个最终值。接下来你的 xy=0 和 xy=1 应该像这样交换:

 if (ox == 400) {//this was a larger number then the panel/frame so it went offscreen
xy = 0;//swapped
}
if (ox == 0) {
xy = 1;//swapped
}

关于Java timer&paint组件问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11428555/

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