g.setColor or repaint is not working
I have to design a tetris program for class, whenever a brick falls i am trying to paint over its original location white to clear it off and then paint in its new location in black, to make it look like it is moving
Code java:
import java.awt.*;
import javax.swing.*;
import java.util.Random;
import java.awt.event.*;
import java.util.TimerTask;
import java.util.Timer;
public class TetrisPanel extends JPanel implements KeyListener
{
TetrisLayout tetrisField = new TetrisLayout();
int cellW;
int cellH;
int panelW;
int panelH;
int brickW;
int brickH;
int[][] pos;
Bricks brick;
Timer time;
Color color = Color.BLACK;
public void keyPressed(KeyEvent e)
{}
public void keyReleased(KeyEvent e)
{}
public void keyTyped(KeyEvent e)
{}
public TetrisPanel()
{
setLayout(tetrisField);
brick = new Bricks();
}
public void paintComponent(Graphics g)
{
g.setColor(color);
System.out.println(color.toString());
cellW = tetrisField.getGridWidth();
cellH = tetrisField.getGridHeight();
panelW = this.getWidth();
panelH = this.getHeight();
brickW = (panelW/cellW);
brickH = (panelH/cellH);
pos = brick.getPos();
System.out.println(""+pos[0][0]+" " + pos[0][1]+" "+pos[1][0]+" "+pos[1][1]+" "+pos[2][0]+" "+pos[2][1]+" "+pos[3][0]+" "+pos[3][1]);
g.fillRect(panelW/2+pos[0][0]*brickW, pos[0][1]*brickH, brickW, brickH);
g.fillRect(panelW/2+pos[1][0]*brickW, pos[1][1]*brickH, brickW, brickH);
g.fillRect(panelW/2+pos[2][0]*brickW, pos[2][1]*brickH, brickW, brickH);
g.fillRect(panelW/2+pos[3][0]*brickW, pos[3][1]*brickH, brickW, brickH);
}
public void start()
{
time = new Timer();
time.schedule(new TimerTask()
{
public void run()
{
if(brick.falling == true)
{
color = Color.WHITE;
repaint();
brick.Drop();
color = Color.BLACK;
repaint();
}
}
}
,1000,1000);
}.fillRect(panelW/2+pos[3][0]*brickW, pos[3][1]*brickH, brickW, brickH);
}
something is wrong in the run() section of timerTask. I put in the print statements to see what was happening to the color, and it seems to reset to black every time i call repaint(). why is this happeningggggggggggg
Re: g.setColor or repaint is not working
Quote:
t seems to reset to black every time i call repaint()
There is a call to setColor() in the paintComponent method.
What is the value of the color variable that it is using? What is printed out?
When you call repaint() the JVM does NOT immediately call the paintComponent method. It queues the request and calls paintComponent the next chance it gets when it get control of the GUI/EDT thread.
Your code must be using the GUI's thread so the JVM will not call paintComponent until your code returns control to the JVM.
You will have to set the color and return to the JVM and then later change the color again to the next color you want.