Java Brickbreaker Block Collision Not Functioning Properly - java

I'm currently coding a simple game of brickbreaker, however I've come across a huge roadblock. The collisions I have declared are going off on the wrong bricks sometimes, also there is a lot of internal bouncing of the ball. On top of that the loop that draws the non hit blocks goes out of bounds but no matter how much I've tried tinkering with it I have not been able to fix it. Any help would be extremely appreciated. Thank you in advance.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class brickBreakerApplet extends Applet implements Runnable, KeyListener, MouseListener, MouseMotionListener
{
private int speed;
int currentLine;
int x_pos = 30;
int y_pos = 100;
int x_speed = 1;
int y_speed = 1;
int radius = 5;
int appletsize_x = 400;
int appletsize_y = 300;
int mousex=0;
int mousey=0;
int score=0;
int life=3;
int counter=0;
int[] bricks;
Boolean game=false;
Image background;
private Image dbImage;
private Graphics dbg;
public void init()
{
setBackground (Color.blue);
background = getImage(getCodeBase(), "background.gif");
bricks=new int[50];
for (int x=0; x<50; x++){
bricks[x]=1;
}
currentLine = 10;
addKeyListener(this);
addMouseListener(this);
addMouseMotionListener(this);
}
public void start ()
{
Thread th = new Thread (this);
th.start ();
}
public void stop()
{
}
public void keyPressed(KeyEvent e)
{
if (e.getKeyChar() == 'r'){
x_pos=0;
y_pos=0;
x_speed=1;
y_speed=1;
}
currentLine+=20;
}
public void keyReleased(KeyEvent e)
{
// System.out.println("User released key " + e.getKeyChar());
// currentLine+=20;
}
public void keyTyped(KeyEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
// System.out.println("User clicked mouse " + e.getClickCount() + " times!");
// currentLine+=20;
}
public void mouseEntered(MouseEvent e)
{
// System.out.println("Mouse entered applet at " + e.getX() + " " + e.getY());
// currentLine += 20;
}
public void mouseExited(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
if (game==false){
x_speed=1;
y_speed=-1;
game=true;
}
if (life==0){
x_pos=0;
y_pos=0;
x_speed=1;
y_speed=1;
life=3;
score=0;
game=false;
}
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseMoved(MouseEvent e)
{
mousex=e.getX();
mousey=e.getY();
}
public void mouseDragged(MouseEvent e)
{
}
public void destroy()
{
}
public void run ()
{
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while (true)
{
if (x_pos > appletsize_x - radius)
{
if (x_speed==1){
x_speed = -1;
}
if (x_speed==2){
x_speed = -2;
}
}
else if (x_pos < radius)
{
if (x_speed==-1){
x_speed = +1;
}
if (x_speed==-2){
x_speed= 2;
}
}
else if (y_pos < radius)
{
y_speed = +1;
}
else if (y_pos > appletsize_y - radius)
{
death();
}
if (game==true){
x_pos += x_speed;
y_pos += y_speed;
//HITTING TWICE, LOTS OF ERRORS WHILE RUNNING CODE, ASK SIR FOR ASSISTANCE TOMORROW. LOOKS PRETTY GOOD THOUGH.
counter=0;
for (int y=0; y<5; y++){
for (int x=0; x<10; x++){
if (y_pos-(radius)==(40+y*10) &&((x_pos+(radius)>=(x*40) && (x_pos+radius<= 40+(x*40)))) && bricks[counter]==1 && y_speed==-1){
bricks[counter]=0;
score++;
y_speed=1;
}
counter++;
}
}
counter=0;
for (int y=0; y<5; y++){
for (int x=0; x<10; x++){
if (y_pos+(radius)==(30+y*10) && ((x_pos+(radius)>=(x*40) && (x_pos+radius<= 40+(x*40)))) && bricks[counter]==1 && y_speed==1){
bricks[counter]=0;
score++;
y_speed=-1;
}
counter++;
}
}
counter=0;
for (int y=0; y<5; y++){
for (int x=0; x<10; x++){
if (x_pos+radius==(x*40) && ((y_pos>=(30+(y*10)) && (y_pos<= 40+(y*10)))) && bricks[counter]==1){
bricks[counter]=0;
score++;
x_speed=-1;
}
counter++;
}
}
counter=0;
for (int y=0; y<5; y++){
for (int x=0; x<10; x++){
if (x_pos-radius==(40+(x*40)) && ((y_pos>=(30+(y*10)) && (y_pos<= 40+(y*10)))) && bricks[counter]==1){
bricks[counter]=0;
score++;
x_speed=1;
}
counter++;
}
}
if (y_pos >= 280-(radius))
{
{
if ((x_pos+(radius) >= mousex-30) && (x_pos+(radius) <= mousex-20)){
score++;
difficulty();
x_speed=-2;
java.awt.Toolkit.getDefaultToolkit().beep();
}
if ((x_pos+(radius) >= mousex-20) && (x_pos+(radius) <= mousex)){
score++;
difficulty();
x_speed=-1;
java.awt.Toolkit.getDefaultToolkit().beep();
}
if ((x_pos+(radius) >= mousex) && (x_pos+(radius) <= mousex+20)){
score++;
difficulty();
x_speed=1;
java.awt.Toolkit.getDefaultToolkit().beep();
}
if ((x_pos+(radius) >= mousex+20) && (x_pos+(radius) <= mousex+30)){
score++;
difficulty();
x_speed=2;
java.awt.Toolkit.getDefaultToolkit().beep();
}
}
}
}
if (game==false){
x_pos=mousex;
y_pos= 279-radius;
}
repaint();
try
{
Thread.sleep (5);
}
catch (InterruptedException ex)
{
// do nothing
}
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
}
}
public void update (Graphics g)
{
if (dbImage == null)
{
dbImage = createImage (this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics ();
}
dbg.setColor (getBackground ());
dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
dbg.setColor (getForeground());
paint (dbg);
g.drawImage (dbImage, 0, 0, this);
}
public void paint (Graphics g)
{
if (life>0){
g.drawImage(background,0,0,this);
g.setColor (Color.cyan);
g.fillOval (x_pos - radius, y_pos - radius, 2 * radius, 2 * radius);
g.setColor (Color.blue);
g.fillRect (mousex-30, 280, 60, 5);
g.setFont(new Font("Comic Sans MS", Font.PLAIN, 20));
g.setColor (Color.cyan);
g.drawString ("Score: "+score, 5,20);
g.drawString ("Life: "+life, 330,20);
counter=0;
for (int y=0; y<5; y++){
for (int x=0; x<10; x++){
if (bricks[counter]==1){
g.setColor(Color.blue);
g.fillRect(x*40, 30+(y*10),40,10);
g.setColor(Color.black);
g.drawRect(x*40, 30+(y*10),40,10);
}
counter++;
}
}
}
if (life==0){
g.setColor (Color.black);
g.fillRect (0,0,400,400);
g.setColor (Color.white);
g.setFont (new Font("Times New Roman", Font.BOLD, 48));
g.drawString ("GAME OVER", 50, 150);
g.setFont (new Font("Times New Roman", Font.PLAIN, 12));
g.drawString ("To Try Again, Press Screen", 130, 160);
g.drawString ("Your Score Was: "+score, 155, 170);
}
}
public void death ()
{
game=false;
y_pos= 279-radius;
life--;
}
public void difficulty()
{
y_speed=-1;
}
}

Related

Java Applet puzzle picture game

I am making a java sliding puzzle for my project, and i have managed to crop the images and making it move to a blank space, however i am still puzzled on how to know whether the user got the correct solution or not. i wanted to congratulate the user when he gets the correct pattern.
import java.applet.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
public class SlidePuzz extends Applet implements MouseMotionListener,MouseListener {
int gridDim = 3;
int animal = -1;
int pieceDim = 0;
int a; int b;
int gapX = -1; int gapY = -1;
int moveX = -1; int moveY = -1;
Image[][] pieces = new Image[7][7];
int[][] placement = new int[7][7];
String [] images = {"mouse","cat","dog"};
String stage = "grid";
Image img;
public void init() {
setSize(420, 420);
addMouseMotionListener(this);
addMouseListener(this);
}
public void paint(Graphics g) {
if(stage=="grid") {
g.setColor(Color.lightGray);
g.fillRect(0,0,60*gridDim,60*gridDim);
g.setColor(Color.white);
g.fillRect(60*gridDim,0,(7-gridDim)*60,420);
g.fillRect(0,60*gridDim,60*gridDim,(7-gridDim)*60);
g.setColor(Color.black);
for (int i=1; i<7; i++) {
g.drawLine(i*60,0,i*60,460);
g.drawLine(0,i*60,460,i*60);
}
g.setColor(Color.black);
g.fillRect(120,0,180,20);
g.setColor(Color.white);
g.drawString("click to choose "+gridDim+"x"+gridDim+" grid", 145, 15);
} else if (stage=="animal") {
g.setColor(Color.white);
g.fillRect(0,0,420,420);
g.setColor(Color.black);
g.drawString("Please click an animal...", 80, 100);
g.setFont(new Font("Courier New", Font.BOLD, 22));
g.drawString("Mouse", 80, 150);
g.drawString("Cat", 80, 200);
g.drawString("Dog", 80, 250);
} else if (stage=="game") {
if (gapX<0) {
g.setColor(Color.white);
g.fillRect(0,0,420,420);
g.setColor(Color.black);
g.setFont(new Font("Courier New", Font.PLAIN, 12));
g.drawString("Loading image...", 120, 50);
tr = new MediaTracker(this);
img = getImage(getCodeBase(), images[animal]+".jpg");
tr.addImage(img,0);
for(int x=0; x<gridDim; x++) {
for(int y=0; y<gridDim; y++) {
pieces[x][y] = createImage(new FilteredImageSource(img.getSource(),
new CropImageFilter(x*pieceDim, y*pieceDim, pieceDim, pieceDim)));
placement[x][y] = (x==gridDim-1 && y==gridDim-1) ? -2 : -1;
tr.addImage(pieces[x][y],0);
}
}
Random r = new Random();
Boolean placed;
for(int x=0; x<gridDim; x++) {
for(int y=0; y<gridDim; y++) {
// if its the gap, no need to draw anything
if (placement[x][y]==-2) break;
// keep looping until piece is selected thats not already drawn
do {
do {
a = r.nextInt(gridDim);
b = r.nextInt(gridDim);
} while (a==gridDim-1 && b==gridDim-1);
placed = false;
for(int c=0; c<gridDim; c++) {
for(int d=0; d<gridDim; d++) {
if(placement[c][d]==a*10+b) placed=true;
}
}
} while (placed);
// draw on the screen and record what's gone here
g.drawImage(pieces[a][b], x*pieceDim, y*pieceDim, this);
placement[x][y] = a*10+b;
}
}
// record where the gap is
gapX = gridDim-1; gapY = gridDim-1;
// a piece needs to be moved
} else if (moveX>=0){
g.setColor(Color.white);
g.fillRect(moveX*pieceDim, moveY*pieceDim, pieceDim, pieceDim);
b = placement[moveX][moveY]%10;
a = (placement[moveX][moveY]-b)/10;
g.drawImage(pieces[a][b], gapX*pieceDim, gapY*pieceDim, this);
placement[gapX][gapY] = a*10+b;
placement[moveX][moveY] = -2;
gapX = moveX; gapY = moveY;
moveX = -1; moveY = -1;
} else {
for(int x=0; x<gridDim; x++) {
for(int y=0; y<gridDim; y++) {
if (placement[x][y]==-2) continue;
b = placement[x][y]%10;
a = (placement[x][y]-b)/10;
g.drawImage(pieces[a][b], x*pieceDim, y*pieceDim, this);
}
}
}
}
}
public void mouseMoved(MouseEvent me) {
if(stage=="grid") {
int mousePos = me.getX()>me.getY() ? me.getX() : me.getY();
int oldGridSize = gridDim;
gridDim = (mousePos/60)+1;
if(gridDim<3) gridDim=3;
if (gridDim!=oldGridSize) repaint();
}
}
public void mousePressed (MouseEvent me) {
int x = me.getX();
int y = me.getY();
if(stage=="grid") {
stage = "animal";
repaint();
} else if(stage=="animal") {
if(x<150 && x>80 && y<150 && y>130) animal=0;
else if(x<150 && x>80 && y<200 && y>180) animal=1;
else if(x<150 && x>80 && y<250 && y>130) animal=2;
if (animal>-1) {
stage="game";
pieceDim = 420/gridDim;
repaint();
}
} else if(stage=="game") {
x /= pieceDim;
y /= pieceDim;
Boolean right = (x-1==gapX && y==gapY);
Boolean left = (x+1==gapX && y==gapY);
Boolean down = (x==gapX && y-1==gapY);
Boolean up = (x==gapX && y+1==gapY);
if (right || left || down || up) {
moveX = x;
moveY = y;
repaint();
}
}
}
public void update(Graphics g) { paint(g); }
public void mouseDragged (MouseEvent me) {}
public void mouseExited (MouseEvent me) {}
public void mouseEntered (MouseEvent me) {}
public void mouseClicked (MouseEvent me) {}
public void mouseReleased (MouseEvent me) {}
}

Why doesn't the "ball" change colors when intersecting parts of my array? (java)

This code is to a game named brick-breaker. I tried to make the ball change colors when intersecting with the array. I've created an int for the R,G,B values of the custom color, and have these ints be generated on intersect to a number between 1-255
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
import java.util.Random;
public class brickbreaker extends Applet implements MouseListener, Runnable, KeyListener
{
Thread main=new Thread(this);
int mouseX, mouseY;
int paddleX = 200, x,y,height,width, ballX = 100, ballY = 400, xChange = 1, yChange = 4, paddleWidth = 150, pageCt = 1, score = 0;
boolean pause = false, gameover=false;
boolean blocks[][] = new boolean [6][10];
int randomR = 255, randomG = 205, randomB = 155;
Random red = new Random();
Random green = new Random();
Random blue = new Random();
Image buffer;
Graphics bufferG;
String input="";
Font font3 = new Font ("Impact",5,50);
Font font4 = new Font ("Impact",5,150);
Font font5 = new Font ("Impact",5,30);
Color randomColor = new Color(randomR,randomG,randomB);
public void init()
{
resize( 1300,700 );
buffer = createImage(this.getWidth(),this.getHeight());
bufferG = buffer.getGraphics();
this.setLayout (null);
this.addKeyListener(this);
this.addMouseListener(this);
this.resize(1400,700);
main.start();
for(int r=0;r<6;r++)
for(int c=0;c<10;c++)
blocks[r][c] = true;
}
public void drawBlocks(Graphics g)
{
for(int r=0;r<6;r++)
for(int c=0;c<10;c++)
if(blocks[r][c])
g.drawRect(100+100*c, 30+30*r, 100, 30);
}
public void run()
{
if (pageCt==1)
{
while(! gameover)
{
if(pause==false)
{
repaint();
ballX = ballX + xChange;
ballY = ballY + yChange;
Rectangle ballRect = new Rectangle (ballX, ballY, 15, 15);
Rectangle paddleRect = new Rectangle (paddleX,650,paddleWidth,10);
Rectangle boundRect = new Rectangle (0,690,1300,10);
for(int r=0;r<6;r++)
for(int c=0;c<10;c++)
if(blocks[r][c])
{
Rectangle blockRect = new Rectangle (100+100*c, 30+30*r, 100, 30);
if(blockRect.intersects(ballRect))
{
blocks[r][c] = false;
yChange *=-1;
score++;
randomR=red.nextInt(255);
randomB=blue.nextInt(255);
randomG=green.nextInt(255);
if (score==60)
pageCt=4;
}
}
if(ballX < 5 || ballX > 1280)
xChange = -1*xChange;
if(ballY < 5 || ballY > 690)
yChange = -1*yChange;
if (ballRect.intersects (paddleRect))
{
yChange = yChange*-1;
//paddleWidth=paddleWidth-3;
}
if (ballRect.intersects (boundRect))
{
pageCt=2;
}
}
repaint();
try
{main.sleep(20);}
catch(Exception e) {}
}
}
}
public void keyPressed(KeyEvent e) // makes applet do something when clicked.
{
int code = e.getKeyCode();
if(code == e.VK_P)
{
if(pause==false)
pause=true;
else
pause=false;
}
if (pause==false)
{
if(paddleX>20)
{
if(code == e.VK_A)
{
paddleX = paddleX-20;
}
}
if(paddleX<1160)
{
if(code == e.VK_D)
{
paddleX = paddleX+20;
}
}
}
}
public void paint(Graphics g) // Outputs on screen
{
if (pageCt==1)
{
bufferG.setColor(Color.black);
bufferG.fillRect(0,0,1300,700);
bufferG.setColor(Color.blue);
bufferG.setColor(Color.black);
bufferG.fillRect(0,0,this.getWidth(),this.getHeight());
bufferG.setColor(randomColor);
bufferG.fillOval(ballX,ballY,15,15);
bufferG.setColor(Color.white);
bufferG.fillRect(paddleX,650,paddleWidth,10);
drawBlocks(bufferG);
bufferG.setFont(font5);
bufferG.drawString("Score : "+score,10,20);
}
if (pageCt==2)
{
bufferG.setColor(Color.black);
bufferG.fillRect(0,0,1300,700);
bufferG.setColor(Color.white);
bufferG.setFont(font4);
bufferG.drawString("You Lose!", 350,400);
}
if (pause==true)
{
bufferG.setColor(Color.white);
bufferG.setFont(font4);
bufferG.drawString("PAUSED",400,350);
}
if (pageCt==0)
{
bufferG.drawString("- Click to begin -",350,350);
}
g.drawImage(buffer,0,0,this);
}
public void update(Graphics g)
{
paint(g);
}
public void mouseClicked (MouseEvent e) {}
public void keyReleased( KeyEvent e){}
public void keyTyped (KeyEvent e){}
public void mousePressed (MouseEvent e)
{
if(pageCt==0)
{
pageCt++;
repaint();
}
}
public void mouseReleased (MouseEvent e) {}
public void mouseEntered (MouseEvent e){}
public void mouseExited (MouseEvent e) {}
}
The color doesn't change because you aren't updating it with the randomly generated values.
randomR=red.nextInt(255);
randomB=blue.nextInt(255);
randomG=green.nextInt(255);
randomColor = new Color(randomR,randomG,randomB); // <- add this line

AWT-EventQueue-0 Error with KeyListener

I made 2 objects that moves with keylisteners. They move correctly, but in the console I receive this error every time I press a button:
Exception in thread "AWT-EventQueue-0"
java.lang.UnsupportedOperationException: Not supported yet. at
CatchMe.CatchMe.keyTyped(CatchMe.java:197)
My code is as follows:
package CatchMe;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.Timer;
public class CatchMe extends JFrame implements ActionListener, KeyListener {
private Image dbImage;
private Graphics dbg;
int x = 200, y = 300;
int velX, velY;
int velX1, velY1;
int ScoreB1 = 0;
int ScoreR1 = 0;
Timer tm = new Timer(5, this);
long startTime = System.currentTimeMillis();
long onGoing;
String onG;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = (int) screenSize.getWidth();
int height = (int) screenSize.getHeight();
int recX = (width + 100) / 2, recY = (height + 100) / 2;
public CatchMe() {
setSize(width, height);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
tm.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
#Override
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g) {
Rectangle r1 = new Rectangle(recX, recY, 25, 25);
Rectangle r2 = new Rectangle(x, y, 25, 25);
g.setColor(Color.BLUE);
g.fillRect(r1.x, r1.y, r1.width, r1.height);
g.setColor(Color.RED);
g.fillRect(r2.x, r2.y, r2.width, r2.height);
g.setColor(Color.BLACK);
g.fillRect(0, 20, 100, 50);
g.fillRect(100, 20, 100, 50);
g.fillRect(200, 20, 50, 50);
g.setColor(Color.YELLOW);
g.drawString("Score of Blue", 5, 40);
String ScoreB = ScoreB1 + "";
g.drawString(ScoreB, 5, 55);
g.drawString("Score of Red", 110, 40);
String ScoreR = ScoreR1 + "";
g.drawString(ScoreR, 110, 55);
g.drawLine(95, 20, 95, 69);
g.drawLine(200, 20, 200, 69);
g.setColor(Color.RED);
onGoing = (System.currentTimeMillis() - startTime) / 1000;
onG = onGoing + "";
g.setColor(Color.YELLOW);
g.drawString(onG, 220, 50);
System.out.println(onGoing);
if (r1.intersects(r2)) {
if (onGoing <= 60 || (onGoing >= 120 && onGoing < 180)) {
g.setColor(Color.BLUE);
g.drawString("Blue Caught You!", 175, 90);
ScoreB1++;
} else if (onGoing >= 240) {
if (ScoreB1 > ScoreR1) {
Font font = new Font("Jokerman", Font.PLAIN, 50);
g.setColor(Color.BLUE);
g.drawString("BLUE WINS", 600, 400);
} else if (ScoreB1 < ScoreR1) {
Font font = new Font("Jokerman", Font.PLAIN, 50);
g.setColor(Color.RED);
g.drawString("RED WINS", 600, 400);
}
} else {
g.setColor(Color.RED);
g.drawString("Red Caught You!", 175, 90);
ScoreR1++;
}
if (onGoing == 245) {
System.exit(245);
}
repaint();
}
}
#Override
public void actionPerformed(ActionEvent e) {
x = x + velX;
y = y + velY;
recY += velY1;
recX += velX1;
if (x < 0) {
velX = 0;
x = 0;
}
if (x > width - 50) {
velX = 0;
x = width - 50;
}
if (y < 0) {
velY = 0;
y = 0;
}
if (y > height - 40) {
velY = 0;
y = height - 40;
}
//Second square
if (recX < 0) {
velX1 = 0;
recX = 0;
}
if (recX > width - 50) {
velX1 = 0;
recX = width - 50;
}
if (recY < 0) {
velY1 = 0;
recY = 0;
}
if (recY > height - 40) {
velY1 = 0;
recY = height - 40;
}
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_LEFT) {
velX = -5;
velY = 0;
}
if (code == KeyEvent.VK_UP) {
velX = 0;
velY = -5;
}
if (code == KeyEvent.VK_RIGHT) {
velX = 5;
velY = 0;
}
if (code == KeyEvent.VK_DOWN) {
velX = 0;
velY = 5;
}
//Second Rect
if (code == KeyEvent.VK_A) {
velX1 = -5;
velY1 = 0;
}
if (code == KeyEvent.VK_W) {
velX1 = 0;
velY1 = -5;
}
if (code == KeyEvent.VK_D) {
velX1 = 5;
velY1 = 0;
}
if (code == KeyEvent.VK_S) {
velX1 = 0;
velY1 = 5;
}
}
#Override
public void keyReleased(KeyEvent e) {
velX = 0;
velY = 0;
velX1 = 0;
velY1 = 0;
}
public static void main(String[] args) {
CatchMe main = new CatchMe();
}
#Override
public void keyTyped(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
The keyTyped method throws an UnsupportedOperationException because you implemented it this way(or it was automatically generated this way):
#Override
public void keyTyped(KeyEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
Whenever a key is typed, this method is called, so it throws an exception.
To fix it, you need to change the body of this method. If you don't want it to do anything, just leave its body empty:
#Override
public void keyTyped(KeyEvent e) {
}
If you want to do something, you should implement this method according to the desired behavior. For example, this implementation prints a message every time a key is typed:
#Override
public void keyTyped(KeyEvent e) {
System.out.println("A key was typed");
}
#Override
public void keyTyped(KeyEvent e) {
}
Will fix it, you were manually throwing exception when keyTyped is called.

Passing Image in java

Can someone help me with this Error that I get. When I try to pass in the image it gives me Error. This is part of my project, I completed the rest but have problem with the main screen.
Here is the Error:
Project.java:36: cannot find symbol
symbol : method drawImage(java.awt.Image)
location: class java.awt.Graphics
g.drawImage(img);
^
1 error
----jGRASP wedge: exit code for process is 1.
----jGRASP: operation complete.
And this the full Program:
import javax.imageio.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class Project extends JPanel
implements KeyListener, MouseListener, MouseMotionListener {
char shape = 'r';
int x = 0;
int y = 0;
Image img;
boolean start = false;
boolean help = false;
boolean Player1 = false;
boolean Player2 = false;
public Project() {
img = Toolkit.getDefaultToolkit().getImage("mp.jpg");
setFocusable(true);
addKeyListener(this);
addMouseListener(this);
addMouseMotionListener(this);
setSize(400, 400);
}
public void paintComponent(Graphics g) {
// BG
Dimension d = getSize();
g.setColor(getBackground());
// IMAGE ************************************* ERROR
g.drawImage(img);
g.setColor(Color.black);
// Help
g.setFont(new Font("default", Font.BOLD, 12));
if (x >= 900 && x <= 950 && y >= 600 && y <= 650 && start == false) {
g.drawString("Press START to", 960, 620);
g.drawString("start the game.", 960, 635);
}
if (x >= 900 && x <= 950 && y >= 600 && y <= 650 && start) {
g.drawString("Choose a Player", 960, 620);
}
else {
g.setColor(Color.red);
g.fillOval(900, 600, 50, 50);
g.setFont(new Font("default", Font.BOLD, 45));
g.setColor(Color.cyan);
g.drawString("?", 915, 640);
}
// Help
g.setColor(Color.black);
g.fillRect(550, 555, 97, 50);
g.setFont(new Font("default", Font.BOLD, 30));
g.setColor(Color.cyan);
g.drawString("Start", 559, 590);
// Start
if (start) {
g.setColor(Color.black);
g.fillRect(400, 550, 400, 55);
g.setFont(new Font("default", Font.BOLD, 30));
g.setColor(Color.yellow);
g.drawString("PLayer 1", 425, 585);
g.drawString("Player 2", 645, 585);
}
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
shape = e.getKeyChar();
repaint();
}
public void keyReleased(KeyEvent e) {
}
public void mouseEntered(MouseEvent e) {
if (x >= 800 && x <= 850 && y >= 600 && y <= 650) {
help = true;
}
}
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseClicked(MouseEvent e) {// ****** Players Button *******
// Variables
Player1 = false;
Player2 = false;
// Levels
if (start) {
if (x >= 427 && x <= 555 && y >= 564 && y <= 589) {
Player1 = true;
}
if (x >= 648 && x <= 769 && y >= 564 && y <= 587) {
Player2 = true;
}
}
if (x >= 550 && x <= 650 && y >= 560 && y <= 607) {
start = true;
}
else {
start = false;
}
}
public void mouseDragged(MouseEvent e) {
}
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
public static void main(String args[]) {
JFrame f = new JFrame("Project");
Project dc = new Project();
f.getContentPane().add(dc);
f.setSize(1200, 775);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
f.setVisible(true);
}
}
Take a look at the API for Graphics: http://docs.oracle.com/javase/8/docs/api/java/awt/Graphics.html
That class does not contain a method that takes just an image. You probably want something closer to this:
g.drawImage(image, x, y, this);
Where image is the image to be drawn, x and y are the position, and this is the JPanel being drawn in, which is an ImageObserver.
There are other drawImage() methods in the Graphics class that take other parameters as well.
Just use:
g.drawImage(img, 0, 0, null);
Numbers are for (x, y) coordinates you'd like to put your image at and keep last as null (it's for slow sources like internet).
drawImage should contain four arguments.
drawImage(Image, int, int, ImageObserver) // i dont know, why you are passing one argument to this.
Change this line :
From:
g.drawImage(img);
To:
g.drawImage(img,0,0,null);
It works

JPanel tearing even though I double buffer?

EDIT: This is an SSCCE to demonstrate my problem.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
public class Main {
public static BufferedImage map, tileSand, tileSea;
public static void main(String[] args) {
map = new BufferedImage(50, 50, BufferedImage.TYPE_INT_ARGB);
for(int x = 0; x < 50 ; x++){
for(int y = 0; y < 50 ; y++){
boolean colour = Math.random() < 0.5;
if (colour){
map.setRGB(x, y, -256);
} else {
map.setRGB(x, y, -16776961);
}
}
}
tileSand = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
Graphics g = tileSand.getGraphics();
g.setColor(Color.YELLOW);
g.fillRect(0, 0, 32, 32);
tileSea = new BufferedImage(32, 32, BufferedImage.TYPE_INT_ARGB);
g.setColor(Color.BLUE);
g = tileSea.getGraphics();
g.fillRect(0, 0, 32, 32);
Island test = new Main.Island();
test.start();
long start, sleep;
while(true) {
start = System.currentTimeMillis();
test.getCanvas().requestFocus();
test.getCanvas().repaint();
sleep = 15-(System.currentTimeMillis()-start);
try {
Thread.sleep(sleep > 0 ? sleep : 0);
} catch (InterruptedException e) {
}
}
}
static class Island implements Runnable {
private Tile[][] tiles;
private JFrame frame;
private JPanel panel;
private Thread logicThread;
private boolean running = false;
private boolean paused = false;
private Image image;
private Player player;
public Island() {
image = new BufferedImage(1027, 768, BufferedImage.TYPE_INT_ARGB);
player = new Player();
tiles = new Tile[map.getWidth()][map.getHeight()];
int rgb;
for(int x = 0; x < map.getWidth(); x++) {
for(int y = 0; y < map.getHeight(); y++) {
rgb = map.getRGB(x, y);
switch (rgb) {
case -16776961: tiles[x][y] = new Tile("sea");
break;
case -256: tiles[x][y] = new Tile("sand");
break;
}
}
}
makeMap();
makeFrame();
addBindings();
logicThread = new Thread(this);
}
public JPanel getCanvas() {
return panel;
}
public void start() {
running = true;
paused = false;
logicThread.start();
}
public void run() {
long sleep, before;
while(running){
before = System.currentTimeMillis();
player.move();
try {
sleep = 15-(System.currentTimeMillis()-before);
Thread.sleep(sleep > 0 ? sleep : 0);
} catch (InterruptedException ex) {
}
while(running && paused);
}
paused = false;
}
private void makeFrame() {
frame = new JFrame("Island");
panel = new JPanel(){
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) image.getGraphics();
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, 1024, 768);
long xl, yl;
xl = player.getLocation().x-512;
yl = player.getLocation().y-384;
int x2, y2;
x2 = (int) Math.floor(xl / 32);
y2 = (int) Math.floor(yl / 32);
int xoffset, yoffset;
xoffset = (int) (xl % 32);
yoffset = (int) (yl % 32);
for(int x = x2; x < x2+40; x++) {
for(int y = y2; y < y2+40; y++) {
if (x < tiles.length && x > 0 && y < tiles[0].length && y > 0) {
g2d.drawImage(tiles[x][y].getContent(), (x-x2)*32 - xoffset, (y-y2)*32 - yoffset, null);
}
}
}
g.drawImage(image, 0, 0, null);
}
};
panel.setPreferredSize(new Dimension(1024, 768));
panel.setIgnoreRepaint(true);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
private void addBindings() {
InputMap inputMap = panel.getInputMap();
ActionMap actionMap = panel.getActionMap();
inputMap.put(KeyStroke.getKeyStroke("Q"),"hold-sprint");
actionMap.put("hold-sprint", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
player.sprint(true);
}
});
inputMap.put(KeyStroke.getKeyStroke("released Q"),"release-sprint");
actionMap.put("release-sprint", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
player.sprint(false);
}
});
inputMap.put(KeyStroke.getKeyStroke("RIGHT"),"hold-right");
actionMap.put("hold-right", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
player.right(true);
}
});
inputMap.put(KeyStroke.getKeyStroke("released RIGHT"),"release-right");
actionMap.put("release-right", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
player.right(false);
}
});
inputMap.put(KeyStroke.getKeyStroke("DOWN"),"hold-down");
actionMap.put("hold-down", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
player.down(true);
}
});
inputMap.put(KeyStroke.getKeyStroke("released DOWN"),"release-down");
actionMap.put("release-down", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
player.down(false);
}
});
inputMap.put(KeyStroke.getKeyStroke("LEFT"),"hold-left");
actionMap.put("hold-left", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
player.left(true);
}
});
inputMap.put(KeyStroke.getKeyStroke("released LEFT"),"release-left");
actionMap.put("release-left", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
player.left(false);
}
});
inputMap.put(KeyStroke.getKeyStroke("UP"),"hold-up");
actionMap.put("hold-up", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
player.up(true);
}
});
inputMap.put(KeyStroke.getKeyStroke("released UP"),"release-up");
actionMap.put("release-up", new AbstractAction() {
public void actionPerformed(ActionEvent e) {
player.up(false);
}
});
}
private void makeMap() {
for(int x = 0; x < tiles.length; x++) {
for(int y = 0; y < tiles[0].length; y++) {
switch (tiles[x][y].getType()) {
case "sea": tiles[x][y].setContent(tileSea);
break;
case "sand": tiles[x][y].setContent(tileSand);
break;
}
}
}
}
}
static class Player{
private Point location;
private int xspeed, yspeed;
private boolean left, up, right, down, sprint;
public Player() {
location = new Point(0, 0);
left = false;
up = false;
right = false;
down = false;
sprint = false;
xspeed = yspeed = 0;
}
public void left(boolean state){
left = state;
}
public void up(boolean state){
up = state;
}
public void right(boolean state){
right = state;
}
public void down(boolean state){
down = state;
}
public void sprint(boolean state) {
sprint = state;
}
public void move() {
if (sprint) {
if (left) {
if(xspeed>-10)
xspeed--;
} if (right) {
if(xspeed<10)
xspeed++;
} if (up) {
if(yspeed>-10)
yspeed--;
} if (down) {
if(yspeed<10)
yspeed++;
}
} else {
if (left) {
if(xspeed>-5)
xspeed--;
} if (right) {
if(xspeed<5)
xspeed++;
} if (up) {
if(yspeed>-5)
yspeed--;
} if (down) {
if(yspeed<5)
yspeed++;
}
}
if (!sprint) {
if (xspeed > 5) {
xspeed--;
} if (xspeed < -5) {
xspeed++;
} if (yspeed > 5) {
yspeed--;
} if (yspeed < -5) {
yspeed++;
}
}
if (!left && !right) {
if (xspeed > 0) {
xspeed--;
} if (xspeed < 0) {
xspeed++;
}
} if (!up && !down) {
if (yspeed > 0) {
yspeed--;
} if (yspeed < 0) {
yspeed++;
}
}
location.x = location.x + xspeed;
location.y = location.y + yspeed;
}
public Point getLocation() {
return location;
}
}
static class Tile {
private String type;
private BufferedImage tile;
public Tile(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setContent(BufferedImage newTile) {
tile = newTile;
}
public BufferedImage getContent() {
return tile;
}
}
}
I have a JPanel with a modified paintComponent method. In this method I draw the relevant tiles from a 2d array to the screen based on the player location. I draw all my tiles to a BufferedImage and then I apply it to the screen at the end of the paint method. In theory this should not create tearing as I am double buffering? Here is the appropriate code, image is just a BufferedImage with the dimensions of the screen:
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) image.getGraphics();
g2d.setColor(Color.BLACK);
g2d.fillRect(0, 0, 1024, 768);
long xl, yl;
xl = player.getLocation().x-512;
yl = player.getLocation().y-384;
int x2, y2;
x2 = (int) Math.floor(xl / 32);
y2 = (int) Math.floor(yl / 32);
int xoffset, yoffset;
xoffset = (int) (xl % 32);
yoffset = (int) (yl % 32);
for(int x = x2; x < x2+40; x++) {
for(int y = y2; y < y2+40; y++) {
if (x < tiles.length && x > 0 && y < tiles[0].length && y > 0) {
g2d.drawImage(tiles[x][y].getContent(), (x-x2)*32 - xoffset, (y-y2)*32 - yoffset, null);
}
}
}
g.drawImage(image, 0, 0, null);
}
I think the tearing could possibly be caused by the player's location changing over the duration of the paint method causing the tiles not to match up, the faster the player goes the more obvious the effect is. However I get the players location at the start and store it in two longs, I was under the impression that longs are passed by value not reference so the player location should be constant whilst the method runs.
I am happy to provide more code :), and thanks in advance.
Just so if people find my question and wonder what I ended up doing to "fix" it, switch over to c++ and SDL or some other image library before you are to far into your project, it's simply better for this kind of thing.

Categories