Java计时器和绘图组件问题

时间:2012-07-11 08:29:52

标签: java swing user-interface timer paint

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

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();
    }
}

1 个答案:

答案 0 :(得分:2)

您的框架/面板大小的坐标已关闭,您应该动态计算,或者具有final值。接下来你的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
        }