Results 1 to 2 of 2
- 12-07-2011, 10:19 PM #1
Senior Member
- Join Date
- Nov 2011
- Location
- Turkey
- Posts
- 378
- Blog Entries
- 24
- Rep Power
- 2
How does frame.repaint and paintComponent work?
Hi,
Here is my code:
Java Code:import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class SimpleGui3C implements ActionListener { JFrame frame; public static void main(String[] args) { SimpleGui3C gui = new SimpleGui3C(); gui.go(); } public void go() { frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton button = new JButton("Change colors!"); button.addActionListener(this); MyDrawPanel drawPanel = new MyDrawPanel(); frame.getContentPane().add(BorderLayout.SOUTH,button); frame.getContentPane().add(BorderLayout.CENTER,drawPanel); frame.setSize(300,300); frame.setVisible(true); } @Override public void actionPerformed(ActionEvent arg0) { frame.repaint(); } }This code just works fine, every time I click the button the drawpanel gets either an orange color or red color depending on the random number i.Java Code:import java.awt.Color; import java.awt.Graphics; import javax.swing.JPanel; public class MyDrawPanel extends JPanel { public void paintComponent(Graphics g) { int i; i = (int) (Math.random()*100); if (i<50) { g.setColor(Color.red); g.fillRect(i,i,100,100); } else { g.setColor(Color.orange); g.fillRect(i,i,100,100); } System.out.println(i); } }
This is in method paintComponent as you can see. But my actionPerformed on button clicked is just frame.repaint.
How is paintComponent triggered in this code, can anyone explain me?
Thanks.
- 12-07-2011, 11:52 PM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,546
- Rep Power
- 11
Re: How does frame.repaint and paintComponent work?
Painting in AWT and Swing
(And remember that your JFrame instance is also an instance of Component.)
Similar Threads
-
repaint() and revalidate() doesn't work in my JContentPane
By bigjo in forum AWT / SwingReplies: 3Last Post: 11-20-2011, 05:50 PM -
Help with using Swing's 'paintComponent' and 'repaint' methods
By dpdwilson in forum AWT / SwingReplies: 0Last Post: 10-24-2011, 09:26 PM -
repaint() does not recall an override method paintComponent(), why is that?
By ilovevcoffe in forum AWT / SwingReplies: 3Last Post: 02-04-2011, 06:30 AM -
repaint class doesnt work anymore... dunno why..
By Addez in forum New To JavaReplies: 9Last Post: 11-07-2009, 09:10 PM -
mouse click do not work after repaint
By nobody in forum Java 2DReplies: 8Last Post: 12-07-2008, 04:43 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks