This week's book giveaway is in the JavaScript forum.
We're giving away four copies of JavaScript Promises Essentials and have Rami Sarieddine on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes thread problem Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of JavaScript Promises Essentials this week in the JavaScript forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "thread problem" Watch "thread problem" New topic
Author

thread problem

ashutosh singh rajkumar
Greenhorn

Joined: Sep 19, 2008
Posts: 1
in d following code when i run the code then after clicking on "right" button ball dont move continuously.After clicking, ball disappears and after specified time it appears again.i want it to move continuously,,,,,,,wat should i do???

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class MyBall extends JFrame
{
int x1=20,y1=50,w=20,h=20;
boolean b=false;
MyPanel panel;
String str="click on start to start the game";
JButton button;

public static void main(String[] s)
{
MyBall ob=new MyBall();
ob.go();
}

public void go()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel=new MyPanel();
add(panel);
ActionListener listener=new MyListener();
addButton("start",listener);
addButton("right",listener);

setSize(400,400);
setVisible(true);
}

public void addButton(String str,ActionListener listener)
{
button=new JButton(str);
button.addActionListener(listener);
panel.add(button);
}

class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent ae)
{
if(ae.getActionCommand().equals("start"))
{
b=true;
str="";
panel.repaint();
}

if(ae.getActionCommand().equals("right"))
{
for(int i=0;i<60;i++)
{
x1+=5;
panel.repaint();
try
{
Thread.sleep(100);
}
catch(Exception e){}
}
}

}
}

class MyPanel extends JPanel
{
public void paintComponent(Graphics g)
{
g.setColor(Color.white);
g.fillRect(0,0,this.getWidth(),this.getHeight());
g.setColor(Color.green);
g.drawString(str,150,150);

if(b)
{
g.setColor(Color.red);
g.fillOval(x1,y1,w,h);
}
}
}
}
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19755
    
  20

Please Use Code Tags in the future, with proper indentation.

You should read JProgressBar Doesn't Update first to see why this is happening. Although it describes a JProgressBar it applies for your problem as well.

Next you should look at javax.swing.SwingWorker, and find some examples. I've posted a few of them myself here, so using the search should help you.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: thread problem