我正在尝试使用func1()和func2()通过使用计时器来移动圆圈。但它们根本没有移动。那么,如何从两个函数中获取'x'和'x1'值到paintComponent。这是代码:
import java.awt.Graphics;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TC extends JPanel
{
static Timer t1;
static Timer t2;
static Timer t3;
static TimerTask tt1;
static TimerTask tt2;
static int x = 0 ,x1 = 500;
static int y = 100,i = 0,j = 0;
static Graphics g1;
static int var = 0;
public static void main(String[] args) throws Exception
{
TC T = new TC();
JFrame f = new JFrame("TC");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JFrame ff = new JFrame("2nd Frame");
ff.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
TextField tf1 ,tf2;
f.getContentPane().setLayout(null);
tf1 = new TextField();
tf2 = new TextField();
tf1.setBounds(50,50, 200, 20);
tf2.setBounds(50,100, 200, 20);
f.add(tf1);
f.add(tf2);
TC.func1(f,tf1);
TC.func2(f,tf2);
ff.add(T);
ff.setSize(1000, 700);
ff.setVisible(true);
f.setSize(1000,700);
f.setVisible(true);
}
static void func1(JFrame f,TextField tf1)
{
//int delay = 100;
TC T = new TC();
t1 = new Timer();
tt1 = new TimerTask()
{
@Override
public void run()
{
x += 1;
y = 100;
System.out.println(x);
System.out.println(y);
tf1.setText(Integer.toString(x));
if(x1 == x)
{
t1.cancel();
tt1.cancel();
}
};
};
t1.scheduleAtFixedRate(tt1,0,50);
}
static void func2(JFrame f,TextField tf2)
{
t2 = new Timer();
tt2 = new TimerTask()
{
@Override
public void run()
{
x1 -= 1;
y = 100;
System.out.println(x1);
System.out.println(y);
tf2.setText(Integer.toString(x1);
if(x1 == x)
{
t2.cancel();
tt2.cancel();
}
}
};
t2.scheduleAtFixedRate(tt2,0,50);
}
@Override
public void paint(Graphics g)
{
super.paintComponent(g);
g1 = g;
g.fillOval(x, y, 10, 10);
g.fillOval(x1, y, 10, 10);
}
}
答案 0 :(得分:0)
每次移动它时,你可能必须重新绘制圆圈。