| 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: 19216
|
|
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
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: thread problem
|
|
|