i want to use a thread make the message flash,and i write a test application as below,but it could not work as i want. could someone tell me what's wrong? thanks a lot
import java.awt.*; import javax.swing.*; public class test { public static void main(String[] args) { testFrame frame = new testFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); } }
/** A frame that contains a message panel */ class testFrame extends JFrame { public testFrame() { setTitle("test"); setSize(WIDTH, HEIGHT); //add panel to frame testPanel panel = new testPanel(); Thread t = new Thread(panel); t.start(); Container contentPane = getContentPane(); contentPane.add(panel); } public static final int WIDTH = 400; public static final int HEIGHT = 300; }
/** A panel that displays a message */ class testPanel extends JPanel implements Runnable { int flag = 1; public void paintComponent(Graphics g) { super.paintComponent(g); if (flag == 1) g.setColor(Color.BLUE); else g.setColor(Color.yellow); g.drawString("test", MESSAGE_X, MESSAGE_Y); }
public void run() { flag = -flag; try { Thread.sleep(250); } catch (InterruptedException e) { } } public static final int MESSAGE_X = 75; public static final int MESSAGE_Y = 100; }