Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
    Bookmark Topic Watch Topic
  • New Topic

PROBLEM!! Strang effect  RSS feed

Aleksandar Mitrev
Posts: 25
  • Mark post as helpful
  • send pies
  • Report post to moderator
I made java code to draw lane on a JPanel. When I COMPILE and RUN the code there are no mistake but I can't see the lane on the JPanel the strang is thet if I run the program several times I'm able to see the lane on the JPanel example I run the code 20 times i cen see the lane once
Can someone tell me what is the problem . Sorry about my English
Here is the code:

import javax.swing.*;
import java.awt.*;
import java.lang.Object.*;

public class Proba extends JPanel {

public Proba(Container c) {
setSize(200, 200);


public void drawing() {
int W = getWidth();
int H = getHeight();
Graphics g = getGraphics();
g.drawLine(1, H-1, 20, H-8);

public static void main(String args[]) {

JFrame win = new JFrame();
Container cp = win.getContentPane();
Proba panel = new Proba(cp);


Rob Spoor
Posts: 21044
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Report post to moderator
drawing() is only called in the constructor. Each time the panel gets repainted (which includes the first showing), the entire panel is cleared and completely repainted. That removes your drawing.

Instead, override paintComponent and add it there:

Slightly better would be to pass the graphics object from paintComponent to drawing instead of using getGraphics(). That also will include the drawing when printing the component.
Jelle Klap
Posts: 1952
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Report post to moderator
Also note that the Swing API should not be invoked from any other thread than the Event Dispatch Thread (EDT), as it is not thread-safe.
Any calls from within paintComponent() will execute on the EDT, but the code executed in the main method will not, but should.
Like (for instance):

Getting more familiar with the Swing API in general might be more usefull right now, but this is definately something to keep in mind, and look back at later on.
[ March 21, 2008: Message edited by: Jelle Klap ]
Nathan Pruett
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Report post to moderator
Please don't post multiple copies of the same question. If you need to edit the content of a post, or change the title of the post, these can be accomplished through the "Edit Post" action (it's the icon that looks like a pencil and paper in the row of icons above each post). Closing this thread, further responses can be found in the other thread.
    Bookmark Topic Watch Topic
  • New Topic
Boost this thread!