我试图创建这个对象正在工作的图形对象 timer/timerTask。我可以为单个对象工作,但如果我创建新对象,它就不能按我想要的那样工作。我想像俄罗斯方块一样工作。
这是我的代码
那是我的第一级散文
import javax.swing.*;
import java.awt.*;
import java.util.Timer;
import java.util.*;
public class prosek extends JPanel{
public static int boyut; // size
public static int koordinatx; //coordx
public static int koordinaty; //coordy
public static boolean tekrar; //repeat
public static int yukseklik; //height
private Timer timer;
private LinkedList<TimerTask> taskList=new LinkedList<TimerTask>();
public prosek(){
yukseklik=140;
tekrar=false;
koordinatx=0;
koordinaty=-20;
boyut=20;
startSampling();
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d=(Graphics2D)g;
g2d.setColor(Color.RED);
g2d.fillRect(koordinatx, koordinaty, boyut+1, boyut+1);
g2d.dispose();
}
public void moveRectangle()
{
if(yukseklik<=140)
{
if(koordinaty<140) koordinaty=koordinaty+boyut;
else
{
yukseklik-=20;
stopSampling();
}
}
}
void startSampling(){
TimerTask task=new TimerTask(){
public void run() {
moveRectangle();
repaint();
}
};
Timer timer=new Timer();
timer.scheduleAtFixedRate(task,0, 500);
taskList.add(task);
}
void stopSampling(){
if(taskList.isEmpty()){
return;
}
taskList.removeFirst().cancel();
}
}
------------
That's my second class prosekt
import javax.swing.*;
import java.awt.*;
public class prosekt extends JFrame {
public prosekt(){
Container container=getContentPane();
container.setLayout(new GridLayout(0,1));
container.add(new prosek());
setSize(100,200);
setVisible(true);
add(container);
}
public static void main(String args[])
{
prosekt p=new prosekt();
}
}