There is a panel that on the form in the paintComponent method I draw a string. But when launched from Netbeans, and just a jar file for about one and a half seconds, a window like a redraw appears.

public class MyPanel extends JPanel { public void paintComponent( Graphics g ) { super.paintComponent( g ); Font textFont = new Font( "SanSerif", Font.BOLD, 20 ); String text = "This is text for testing"; g.setFont( textFont ); g.drawString( text, 10, 100 ); Graphics2D g2 = ( Graphics2D) g; } } 

but if you remove g.setFont (textFont); then everything will work very quickly and leave it like this:

 public class MyPanel extends JPanel { public void paintComponent( Graphics g ) { super.paintComponent( g ); Font textFont = new Font( "SanSerif", Font.BOLD, 20 ); String text = "This is text for testing"; g.drawString( text, 10, 100 ); Graphics2D g2 = ( Graphics2D) g; } } 

if I'm after Graphics2D g2 = ( Graphics2D) g; add

 FontRenderContext context = g2.getFontRenderContext(); Rectangle2D textBounds = textFont.getStringBounds( text, context ); 

it will run a little longer, again with a non-redrawn window.

    1 answer 1

    The delay is really due to setFont, I don’t know if it will get rid of it. I am not an expert on GUI, but I can say that regular creation of a Font object, String, in a drawing stream is not a very good solution. Here is a list of what you might try:

    1. what you can do is to put their announcement out of the cycle (if it is possible of course);
    2. try to make setFont immediately after creating the component (before the first drawing);
    3. using the font metrics, find the region that will change, and update only it (and use the setfont only for this object, if possible, of course);
    4. draw your text in a separate buffer, and draw it on your component (read on double buffering);
    5. You can also try to finish the text in a separate stream (so as not to delay the drawing of the window itself):
     public void paintComponent ( final Graphics g ) { super.paintComponent ( g ) ; Runnable writer = new Runnable() { @ Override public void run () { Font textFont = new Font ( "SanSerif", Font.BOLD, 20 ) ; String text = "This is text for testing" ; g.setFont ( textFont ); g.drawString ( text, 10, 100 ) ; } }; new Thread (writer).start (); } 

    Well, it's worth noting that for the first time I see the paintComponent method override it instead of paint.

    UP: if it is critical for you, you can simply make a “flash-screen” - displaying a picture instead of the main window until it is rendered :)

    • Here is another link found on the official website: [Painting in AWT and Swing] [1]. [1]: java.sun.com/products/jfc/tsc/articles/painting/index.html - jmu
    • 5 - do not do this at all. It is very dangerous to perform GUI operations from another thread. But it makes sense not to create a font every time. - cy6erGn0m