• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to call paintComponent in JPanel?

 
Charlie Wall
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys

I need help solving the following problem: How can I make a call to paintComponent within the JPanel-class, from another Class?

In class TestClass:



In class MyPanel:

 
Campbell Ritchie
Marshal
Posts: 52549
119
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Will that actually compile? You have correctly created frame but kept it as a local variable in the constructor. Move the rest of the code into the constructor and lose the initComponents method, and you should be all right.

You override paintComponent and never call it. If you ever need to invoke it, you call repaint(). You do not need getContentPane() because you can simply write add(). You can use an anonymous class, as Piet Souris does here.Note:-
  • 1: Override annotation to protect against tiny spelling errors.
  • 2: Give the method protected access.
  • 3: the super. call is necessary when there is any movement on screen, so as to remove the “old” display.
  • I haven't tested that code.

    If you look in the Java Tutorials, you find they have new names for the locations in border layout. CENTER is unchanged, however.
     
    Charlie Wall
    Greenhorn
    Posts: 6
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thanks a lot! That cleared things out.
     
    Ulf Dittmer
    Rancher
    Posts: 42970
    73
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    You override paintComponent and never call it.

    Which is as it should be. You should never call any of the painting methods directly, but rather call "repaint" on the component.
     
    Campbell Ritchie
    Marshal
    Posts: 52549
    119
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    You're welcome
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!