Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows erases content of JFrame when overlapping

I create and display a window using JFrame having set it just very basic properties.

public FrameVertices( String sTitle, Graph mMap, int iMul ) {
    super( sTitle );

    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    setSize ( 300, 300 );
    setLocation ( 600, 300 );
    setVisible ( true);

    this.iMul = iMul;
    this.gGraph = mMap;
}

Then I paint something inside the window using paint() method.

The problem is that when some other windows cover my JFrame and then uncover it, the content of the JFrame is not repainted - unless I resize or min/max the JFrame.

Am I missing something?

like image 530
Protechnologia.pl Avatar asked Feb 20 '23 12:02

Protechnologia.pl


1 Answers

It is not good practice to paint directly to a JFrame. A better approach is to override paintComponent() in a JPanel and add the JPanel to the JFrame:

Test.java:

public class Test extends JFrame {

    public static void main(String[] args) {

       SwingUtilities.invokeLater(new Runnable() {
          public void run() {
           new Test().createUI();
          }
       });

    }

  void createUI() {

             setSize(500,500);
             getContentPane().add(new MyPanel());
             setVisible(true);      
       }
}

MyPanel.java:

class MyPanel extends JPanel {

    @override
    public void paintComponent(Graphics g) {
      super.paintComponent(g);
      //paint what you want here
      g.drawString("Hello world",250,250);
    }
}

However if you must, I'd suggest adding a Window FocusListener and call repaint() on the JFrame instance when its brought into focus: http://docs.oracle.com/javase/tutorial/uiswing/events/windowlistener.html

via the method windowGainedFocus(WindowEvent e) or windowStateChanged(WindowEvent e) or windowActivated(WindowEvent e) calling repaint() in 1 of these methods will then call the paint() method.

like image 85
David Kroukamp Avatar answered Mar 02 '23 18:03

David Kroukamp