I am beginner in Java and I am having difficulties creating bufferstaregy in a class which extends JPanel but not canvas. Can some one show how to add buffer strategy here. I wrote very simplified code which illustrates my problem. I move rectangle in x and y position, however I can't see smooth movement of the rectangle at high speed. I hope that buffer strategy can solve this problem. I might be wrong. In any case what should I do here if I want to see smooth rectangle movement? I would be very grateful for any help. I am stucked at this position for a few days.
import javax.swing.*;
import java.awt.*;
public class simpleAnimation {
public static void main(String args[]){
Runnable animation = new moveAnimation();
Thread thread = new Thread(animation);
thread.start();
}
}
// Creates window and performs run method
class moveAnimation implements Runnable{
JFrame frame;
int x = 0;
int y = 0;
boolean running = true;
moveAnimation(){
frame = new JFrame("Simple Animation");
frame.setSize(600,600);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void run() {
while(running == true){
if(x<=500 || y<=500){
x++;
y++;
}
frame.add(new draw(x, y)); // I create new object here from different class which is below
frame.setVisible(true);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
}
// I use this class to draw rect on frame
class draw extends JPanel{
int x;
int y;
draw(int x, int y){
this.x=x;
this.y=y;
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.BLACK);
g2.fillRect(0,0,getWidth(),getHeight());
g2.setColor(Color.GREEN);
g2.fillRect(x,y,50,50);
}
}
You can't really create a BufferStrategy on a class which extends JPanel using only that class the best option is too set "setDoubleBuffered" true this allows for a buffer of 2 but it doesn't exactly create an accessible bufferStrategy I would advise using a Canvas which you add to a JPanel that way you can get a bufferStrategy as well as smoother better controlled graphics