Search code examples
javaswinggraphicspaintcomponent

Java Graphics Will Not Display


Here is my code:

package survival;
import javax.swing.*;
import java.awt.*;

public class Survival extends JFrame { 
    private static int applicationWidth = 1400;
    private static int applicationHeight = 900;  

    public Survival() {
        setTitle("Survival");
        setResizable(false);
        setSize(applicationWidth, applicationHeight);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public void paint(Graphics g) {
        g.drawString("Test", 0, 0);
    }

    public static void main(String[] args) {
        new Survival();
    }
}

Why isn't "Test" showing up?


Solution

  • You need to invoke paint() method of super class. (Article - Painting in AWT and Swing)

     public Survival() {
            setTitle("Survival");
            setResizable(false);
            setSize(applicationWidth, applicationHeight);
            setVisible(true);
    
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            repaint();
        }
    
        public void paint(Graphics g) {
            super.paint(g);    
            g.drawString("Test", 120, 120); //change the co-odrinates
        }
    

    Override the paintComponent of JPanel.

     public Survival() {
            setTitle("Survival");
            setResizable(false);
            setSize(applicationWidth, applicationHeight);
            setVisible(true);
            add(new DrawPanel());
            setDefaultCloseOperation(EXIT_ON_CLOSE);
         }
    
       class DrawPanel extends JPanel
       {
        @Override
        protected  void paintComponent( Graphics g){
           g.drawString("Test", 220,220);
          }
       }