hi,
Thanks for ur reply, i rewrite the code that i have posted, following is the complete code, i add a debug code on line 41 which will print two lines to STDOUT, it proofs that the paintComponent() will be called twice. i think the paintComponent() first call on line 54, second call on line 18, i don't know it is right or not. i also can't understand why a blue rectangle will be painted first. Due to line 42, i think a red rectangle will be painted at the first call. Any idea? Thanks
1 public class PaintImmediatelyTest extends JPanel
2 implements ActionListener{
3
4private JButton bt1;
5private JButton bt2;
6private JPanel jpl;
7
8public PaintImmediatelyTest() {
9
10setLayout(new FlowLayout());
11
12bt1 = new JButton("paintImmediately");
13bt2 = new JButton("repaint");
14
15bt1.addActionListener(this);
16bt2.addActionListener(this);
17
18jpl = new JPanelEx();
19jpl.setPreferredSize(new Dimension(200 , 200));
20
21add(bt1);
22add(bt2);
23add(jpl);
24}
25
26public void actionPerformed(ActionEvent e) {
27if (e.getActionCommand().equals("repaint")) jpl.repaint();
28else jpl.paintImmediately(50 , 50 , 100 , 100);
29
30try { Thread.sleep(3000); }
31catch(Exception err) {}
32}
33
34class JPanelEx extends JPanel {
35int backColor = 0xFF; //0xFF is blue, 0xFF0000 is red
36
37public void paintComponent(Graphics g) {
38
39super.paintComponent(g);
40
41System.out.println(backColor);
42backColor = backColor == 0xFF0000 ? 0xFF : 0xFF0000;
43Dimension dim = getSize();
44g.setColor(new Color(backColor));
45g.fillRect(0 , 0 , dim.width , dim.height);
46}
47}
48
49public static void createAndShowGUI() {
50
51try {
52 UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
53 } catch (Exception evt) {}
54 JFrame f = new JFrame("PaintImmediatelyTest");
55 f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
56 JComponent newContentPane = new PaintImmediatelyTest();
57 newContentPane.setOpaque(true);
58
59 f.setContentPane(newContentPane);
60
61 f.setSize(500, 400);
62 f.pack();
63 f.setVisible(true);
64}
65
66public static void main(
String[] args) {
67
68javax.swing.SwingUtilities.invokeLater(new Runnable() {
69 public void run() {
70 createAndShowGUI();
71 }
72 });
73}
74}