Hello folks!
I’ve been building a very basic program on my free time, just for fun, it basically draws random numbers in a line, then jumps to the next row when the line finishes. However, when reaching the bottom right part of the frame it continues down out of view. What i want it to do is move everything, numbers and background graphics upwards one line, then draw a new black square at the bottom row to draw the new numbers on. I looked around a bit in the Java API docs after a method that could do this for me and i found a method in the Graphics class called copyArea. This method moves everything but i can’t make it display the graphics properly, im unsure of what i am doing wrong. Could you guys help?
EDIT: I managed to fix it, im unsure how though XD
Here is the source
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.util.*;
public class MainEngine extends JPanel implements Runnable{
Random rand = new Random();
int letterPosX, letterPosY;
int number;
boolean redraw = false;
boolean running = true;
boolean drawLetters = true;
Graphics2D g2d;
BufferedImage backbuffer;
JPanel p1 = new JPanel();
JFrame f = new JFrame();
Thread CalcLoop;
public static void main(String[] args){
MainEngine me = new MainEngine();
me.initCalculate();
}
public void initCalculate(){
CalcLoop = new Thread(this);
CalcLoop.start();
}
@Override
public void run() {
initgfx();
while(running == true){
try{
updateGraphics();
repaint();
Thread.sleep(1);
}catch(InterruptedException e){}
}
}
public void update(Graphics g){
System.out.println("updating");
paint(g);
}
public void initgfx(){
backbuffer = new BufferedImage(800, 600, BufferedImage.TYPE_INT_RGB);
g2d = backbuffer.createGraphics();
f.setSize(800, 600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(this);
f.setVisible(true);
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, 800, 600);
}
public void updateGraphics(){
if(drawLetters == true){
g2d.setColor(Color.WHITE);
number = rand.nextInt(10);
g2d.drawString("" + number, letterPosX, letterPosY);
letterPosX += 7;
}
if(letterPosX >= 790){
letterPosX = 0;
letterPosY += 11;
}
if(letterPosY >= 600){
g2d.copyArea(0, 0, 800, 600, 0, -11);
g2d.setColor(Color.BLACK);
g2d.drawRect(0, 0, 800, 600);
redraw = true;
g2d.setColor(Color.WHITE);
letterPosY = 589;
}
if(redraw != false){
g2d.setColor(Color.BLACK);
g2d.drawRect(0, 0, 800, 600);
//running = false;
}
}
public void updateLastPos(){
}
public void paint(Graphics g){
g.drawImage(backbuffer, 0, 0, null);
}
}

