Home arrow static arrow Java Programming [Archive] - JButton and Paint
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - JButton and Paint
This topic has 1 reply on 1 page.

Posts:58
Registered: 2/3/03
JButton and Paint  
Jun 29, 2004 2:27 AM



 
Hi, I was wondering if anyone could help me with a problem I have been having for a while. I am simply trying to get a flickering painted image on the screen by pressing a JButton. In more detail, I have a global variable, a JButton with an inner class, that upon clicking will activate a for loop for a number of rotations. If the global variable == 1 then it now == 0 and calls repaint (from inside the JButton inner class) . Then the for loop repeats again and switches the global variable and calls repaint again. The paint method simply displays a square that flashes white and black. Basically all the code is executed within a JButton inner class, it has got to be this way (unless there is something better), as this was only an example and not the actual prupose behind the work I am trying to do.

I have been told many times that it has something to do with threads, about the Jbutton not having finished its own event queue before starting another! Now I am no programmer but I have tried to learn, however I simply don't understand how to get this working. Please please please, could someone help me here. A very simple example like the one above in full code would be really really helpful.

Thanks
 

Posts:8,813
Registered: 10/4/00
Re: JButton and Paint  
Jun 29, 2004 2:48 AM (reply 1 of 1)



 
import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Test3 extends JFrame {  BlinkyPanel blinkyPanel = new BlinkyPanel();  public Test3() {    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    Container content = getContentPane();    content.add(blinkyPanel, BorderLayout.CENTER);    for (int i=0; i<10; i++) blinkyPanel.add(new JLabel("-"+i));    JButton jb = new JButton("Button");    content.add(jb, BorderLayout.SOUTH);    jb.addActionListener(new ActionListener() {      public void actionPerformed(ActionEvent ae) {        blinkyPanel.blink();      }    });    setSize(200,200);  }  public static void main(String[] args) {  new Test3().setVisible(true); }}class BlinkyPanel extends JPanel {  boolean blinkyFlag=false;  public void paintComponent(Graphics g) {    super.paintComponent(g);    g.setColor(Color.red);    if (blinkyFlag) g.fillRect(getWidth()/2-5,getHeight()/2-5,10,10);  }  public void blink() {    new Thread(new Runnable() {      public void run() {        for (int i=0; i<10; i++) {          try { Thread.sleep(1000); } catch (Exception e) {}          blinkyFlag = !blinkyFlag;          repaint();        }      }    }).start();  }}
 
This topic has 1 reply on 1 page.