473,406 Members | 2,371 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

when clicking a JButton animation starts but keys stops working

36
Hello freinds! I m making a game but I m facing a problem that when I click New Game button(defined by me) animation starts. But in the animation keys are not working even the Close button at the right top of the window stops working......

So plz! can anyone help me in solving this problem..........
Mar 17 '08 #1
6 3057
JosAH
11,448 Expert 8TB
Hello freinds! I m making a game but I m facing a problem that when I click New Game button(defined by me) animation starts. But in the animation keys are not working even the Close button at the right top of the window stops working......

So plz! can anyone help me in solving this problem..........
Without reading your code my guess is that you're doing all your work in the AWT
Event dispatching thread so that it can't do anything else. In the worst case
you're using Thread.sleep() for your animation too. Carefully design your threads
for the animation logic, the event listening as well as the drawing of the animation.

kind regards,

Jos
Mar 17 '08 #2
JosAH
11,448 Expert 8TB
@OP: I just found your double post on this subject; I deleted the thread. Don't
double post your single problem but stay in one thread for it; otherwise you
confuse people and people might even try to help you while it's not needed
anymore.

kind regards,

Jos (mod)
Mar 17 '08 #3
pankajs
36
do u mean that Thread.sleep is not suitable for gaming when including actionListener ???
Can u suggest me any different way to animate & adding keyListener?????
Mar 17 '08 #4
JosAH
11,448 Expert 8TB
do u mean that Thread.sleep is not suitable for gaming when including actionListener ???
Can u suggest me any different way to animate & adding keyListener?????
Well, the Thread.sleep() method is fine but not in the AWT event dispatch thread.
You effectively kill the thread for some time and it won't be able to respond to
any user gesture; also reread my previous reply and try to show us some sample
code that may show what and how you're doing things now.

kind regards,

Jos
Mar 17 '08 #5
pankajs
36
here is the full code what I have done till today
It starts autmatically but when I click New Game, no key works
to obtain mainwindow press 'P'
import java.awt.*;
import java.awt.font.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.event.*;

public class mainwin extends JPanel
{
BufferedImage image;
JButton ngame;
Invaders1 inv;
String text = "COMBAT MISSION";
String categories[] = { "Save1","Save2" };
JButton res,game,load,exit,save,cred;
JScrollPane scrollpane;
public mainwin(BufferedImage image)
{
this.image=image;
this.inv = inv;
ngame = new JButton("New Game");
res = new JButton("Resume");
//game = new JButton("New Game");
load = new JButton("Load");
save = new JButton("Save");
cred = new JButton("Credits");
exit = new JButton("Exit");

JList list = new JList(categories);
scrollpane = new JScrollPane(list);
event action = new event();
keyevent kaction = new keyevent();
add(ngame);
addKeyListener(kaction);
ngame.addActionListener(action);
exit.addActionListener(action);
save.addActionListener(action);
load.addActionListener(action);
//game.addActionListener(action);
add(res);
//add(game);
add(load);
add(save);
add(cred);
add(exit);


}

protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
int w = getWidth();
int h = getHeight();
// Draw image, centered.
int x = (w - image.getWidth())/2;
int y = (h - image.getHeight())/2;
g2.drawImage(image, x, y, this);
// Draw text centered over image.
//Font font = g2.getFont().deriveFont(66f);
Font font = new Font("Serif",Font.BOLD+Font.ITALIC,80);
g2.setFont(font);
FontRenderContext frc = g2.getFontRenderContext();
float width = (float)font.getStringBounds(text, frc).getWidth();
LineMetrics lm = font.getLineMetrics(text, frc);
float sx = (w - width)/2;
float sy = (h + lm.getHeight())/2 - lm.getDescent()+180;
g2.setPaint(Color.red);
g2.drawString(text, sx, sy);
}

public class event extends JFrame implements ActionListener
{


private int x,sav=0;
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==ngame)
inv.game();
if(e.getSource()==exit)
{
if(sav==0)
{

x=JOptionPane.showConfirmDialog(null, "Do you want to save your game");
if(x==0)
{
JOptionPane.showInputDialog(null,"Enter the file name");
System.exit(0);
}
else if(x==1)
System.exit(0);
}
else
System.exit(0);
}
else if(e.getSource()==save)
{
sav++;
JOptionPane.showInputDialog(null,"Enter the file name");
}
else if(e.getSource()==load)
{
JFrame f1 = new JFrame();
f1.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
f1.setSize(300,400);
f1.getContentPane().add(scrollpane, BorderLayout.CENTER);
f1.setVisible(true);
}

}
}
public class keyevent extends JFrame implements KeyListener
{
public void keyPressed(KeyEvent e)
{
JOptionPane.showMessageDialog(null,"Enter the file name");
int key = e.getKeyCode();
if(key == KeyEvent.VK_LEFT)
{


JOptionPane.showMessageDialog(null,"dfasdme");
}
else if(key == 27)
System.exit(0);
}
public void keyReleased(KeyEvent e)
{}
public void keyTyped(KeyEvent e)
{}
}

public static void main(String[] args) throws IOException
{

String path ="mains.jpg";
BufferedImage image = ImageIO.read(new File(path));
JFrame j1 = new JFrame();
mainwin test = new mainwin(image);
Invaders1 inv = new Invaders1();
inv.game();
j1.add(test);
j1.setSize(800,600);
j1.setVisible(true);
}
}


import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.HashMap;
import java.awt.event.*;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Invaders1 extends Canvas implements KeyListener{
public static final int WIDTH = 800;
public static final int HEIGHT =600;
public static final int SPEED = 10;
public boolean loop=true,explosion=false, Missile=false,invad=false, missile=false, Missile1=false, missile1=false,Monster1=true,Monster2=true, Monster3=true,Monster4=true,Player=true;
public BufferStrategy strategy;
public HashMap sprites;
public Rectangle Ms,Ms1,In1,M1,M2,M3,M4,P;
public int posX,pX,pY,posY,vX,t=0,posX1,posY1,mX,mY,m1X,m1Y,M X,MY,M1X,M1Y,inX,inY,INX,INY;
public long usedTime;

public Invaders1() {
sprites = new HashMap();
INX=inX=posX = posX1=WIDTH;
INY=inY=posY = posY1=HEIGHT/2-150;
vX = 2;
mX=m1X=MX=M1X=pX=40; mY=m1Y=MY=M1Y=pY=350;
P = new Rectangle(pX,pY,32,32);
Ms = new Rectangle(mX,mY,32,32);
Ms1 = new Rectangle(m1X,m1Y,60,15);
M1= new Rectangle(posX,posX,32,32);
M2= new Rectangle(posX-30,posY-30,32,32);
M3= new Rectangle(posX-60,posY-60,32,32);
M4= new Rectangle(posX-90,posY-90,32,32);
In1= new Rectangle(inX,inY,25,25);
addKeyListener(this);
JFrame ventana = new JFrame("Invaders");
JPanel panel = (JPanel)ventana.getContentPane();
setBounds(0,0,WIDTH,HEIGHT);
panel.setPreferredSize(new Dimension(WIDTH,HEIGHT));
panel.setLayout(null);
panel.add(this);
ventana.setBounds(0,0,WIDTH,HEIGHT);
ventana.setVisible(true);
ventana.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
ventana.setResizable(false);
createBufferStrategy(2);
strategy = getBufferStrategy();
requestFocus();
}

public BufferedImage loadImage(String nombre) {
URL url=null;
try {
url = getClass().getClassLoader().getResource(nombre);
return ImageIO.read(url);
} catch (Exception e) {
System.out.println("No image found " + nombre +" de "+url);
System.out.println("location error : "+e.getClass().getName()+" "+e.getMessage());
System.exit(0);
return null;
}
}

public BufferedImage getSprite(String nombre) {
BufferedImage img = (BufferedImage)sprites.get(nombre);
if (img == null) {
img = loadImage(nombre);
sprites.put(nombre,img);
}
return img;
}

public void paintWorld() {
Graphics2D g = (Graphics2D)strategy.getDrawGraphics();
g.setPaint(new TexturePaint(getSprite("oceano.gif"), new Rectangle(t,0,getSprite("oceano.gif").getWidth(),g etSprite("oceano.gif").getHeight())));
g.fillRect(0,0,getWidth(),getHeight());

M1= new Rectangle(posX1,posY1,32,32);
M2= new Rectangle(posX1-30,posY1-30,32,32);
M3= new Rectangle(posX1-60,posY1-60,32,32);
M4= new Rectangle(posX1-90,posY1-90,32,32);
if(Monster1)
g.drawImage(getSprite("bicho.gif"), posX1, posY1,this);
if(Monster2)
g.drawImage(getSprite("bicho.gif"), posX1-30, posY1-30,this);
if(Monster3)
g.drawImage(getSprite("bicho.gif"), posX1-60, posY1-60,this);
if(Monster4)
g.drawImage(getSprite("bicho.gif"), posX1-90, posY1-90,this);



for(int k=0;k<5;k++)
{
In1 =new Rectangle(inX,inY,25,25);
if(invad)
g.drawImage(getSprite("invader.jpg"),inX,inY,this) ;
inX+=30;
inY+=30;
}
if(Player)
g.drawImage(getSprite("nave.gif"),pX,pY,this);
if(explosion)
{
long extime=System.currentTimeMillis();
g.drawImage(getSprite("explosion.gif"),pX,pY,this) ;
long exusTime=System.currentTimeMillis()-extime;
if(exusTime>.25)
explosion=false;
}
if(Missile1)
{m1X=M1X; m1Y=M1Y; Missile1=false;}
if(Missile)
{mX=MX; mY=MY; Missile=false;}
if(missile)
{
g.drawImage(getSprite("misil.gif"),mX,mY,this); mX+=10;
Ms = new Rectangle(mX,mY,32,32);
}
if(missile1)
{
g.drawImage(getSprite("rocket.gif"),m1X,m1Y,this); m1X+=10;
Ms1 = new Rectangle(m1X,m1Y,60,15);
}

if (usedTime > 0)
g.drawString(String.valueOf(1000/usedTime)+" fps",0,HEIGHT-50);
else
g.drawString("--- fps",0,HEIGHT-50);
strategy.show();
}



public void updateWorld() {
posX -= vX;
posX1=posX;
posY1=posY;
if(posX<0)
{
posX=WIDTH;
invad=true;
Monster1=Monster2=Monster3=Monster4=false;
}
INX-=vX;
inX=INX;
inY=INY;

if(INX<0)
{
invad=false;
INX=WIDTH;
Monster1=Monster2=Monster3=Monster4=true;
}
if(P.intersects(M1))
{
Player=false;
explosion=true;
}
if(P.intersects(M2))
{
Player=false;
explosion=true;
}
if(P.intersects(M3))
{
Player=false;
explosion=true;
}
if(P.intersects(M4))
{
Player=false;
explosion=true;
}
if(Ms.intersects(M1))
{
Monster1=false; missile=false;
}
if(Ms1.intersects(M1))
{
Monster1=false; missile1=false;
}
if(Ms.intersects(M2))
{
Monster2=false; missile=false;
}
if(Ms1.intersects(M2))
{
Monster2=false; missile1=false;
}
if(Ms.intersects(M3))
{
Monster3=false; missile=false;
}
if(Ms1.intersects(M3))
{
Monster1=false; missile1=false;
}
if(Ms.intersects(M4))
{
Monster4=false; missile=false;
}
if(Ms1.intersects(M4))
{
Monster4=false; missile1=false;
}

}

public void keyPressed(KeyEvent e)
{
int key = e.getKeyCode();
if(Player)
{
if(key== KeyEvent.VK_LEFT)
{ pX-=10; MX=M1X=pX;}
else if(key== KeyEvent.VK_RIGHT)
{ pX+=10; MX=M1X=pX;}
else if(key== KeyEvent.VK_UP)
{ pY-=10; MY=M1Y=pY;}
else if(key== KeyEvent.VK_DOWN)
{ pY+=10; MY=M1Y=pY;}

else if(key==27)
System.exit(0);
else if(key== KeyEvent.VK_P)
{
if(loop==true)
loop=false;
else
{
loop=true;
game();
}
}
else if(key ==32)
{ Missile=missile=true;}
else if(key==17)
{Missile1=missile1=true;}
P = new Rectangle(pX,pY,32,32);
}
}
public void keyReleased(KeyEvent e)
{}
public void keyTyped(KeyEvent e)
{}
public void game() {
usedTime=1000;
while (loop) {
long startTime = System.currentTimeMillis();
updateWorld();
paintWorld();
t--;
usedTime = System.currentTimeMillis()-startTime;
try {
Thread.sleep(SPEED);
} catch (InterruptedException e) {}
}
}

/*public static void main(String[] args) {
Invaders1 inv = new Invaders1();
inv.game();
}*/
}
Mar 18 '08 #6
JosAH
11,448 Expert 8TB
here is the full code what I have done till today
It starts autmatically but when I click New Game, no key works
to obtain mainwindow press 'P'
That was just too much code (and without the [ code ] tags). All I did was
browse a bit through it but I don't see a separate thread for the game logic and
a separate thread for handling the events. I also find the actual drawing logic
a bit smelly, i.e. you don't use the paintComponent() method (I might have
missed it). Are you able to produce a short piece of code that shows the same
bug? This was just too much code.

kind regards,

Jos
Mar 18 '08 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: metsymani | last post by:
In my web application, I have a search screen coded in ASP.Net. The Search process takes lot of time. So, I need to show a wait page informing the user that "Search is in progress. Please wait" along...
5
by: Alex Stevens | last post by:
Hi All, I'm writing a launcher program which checks for updates and copies them down to the client. However, I would like the user to be able to modify the settings for the launcher. As this...
8
by: Thomas Hallgren | last post by:
I'm writing a small test harness. I have two threads. One that starts the postmaster and another that does all the testing and finally stops the postmaster with a pg_ctl stop. At present, the...
2
by: Mark D. Smith | last post by:
Hi i have to popup (argh) a small page when an animated gif is clicked on. the animation stops as soon as the popup opens. is there a way to restart the gif or prevent it from stopping in the...
3
by: | last post by:
Can someone point me to some good info on how to do somoe simple animation on a form. Specifically, I want to have some tiles that when they are clicked, they flip over in place and reveal a...
44
by: Smokey Grindle | last post by:
I have a list box on my form, but I need to databind it to a data table that is a private member of the form's class... so I basically have Public Class MyForm priate m_MyTable as new datatable...
1
by: rashmi2828 | last post by:
hi i hav done one preloader which is animated.with that animation i am displaying percentage of loaded data.but my loading starts with 37%..before that screen remains blank....
2
by: sokeefe | last post by:
I am trying to edit the GUI of a project in Netbeans. In particular, I am trying to add new JButtons. I get a NullPointerException when I try to add an Event to any given JButton (even ones that...
1
by: sokeefe | last post by:
I am trying to edit the GUI of a project in Netbeans. In particular, I am trying to add new JButtons. I get a NullPointerException when I try to add an Event to any given JButton (even ones that...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.