When you get the graphic context from JPanel get null, why?



  • So, the question is, why are you referring to Graphics zero?

    package CardGame;
    import javax.swing.SwingUtilities;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.BorderFactory;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    

    public class Testing {
    public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable(){
    public void run(){
    createAndShowGUI();
    }
    });
    }

    private static void createAndShowGUI() {
        Tr.db("Created GUI on EDT?"SwingUtilities.isEventDispatchThread()); 
        JPanel p = new JPanel();
        JFrame f = new JFrame("Swing PaintDemo");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        p.setOpaque(true);
        p.setBackground(Color.red);
        Graphics g = p.getGraphics();
        //вот здесь вылетает исключение нул пойнт ексепшн
        //при попытке на панели что нить написать
        g.drawString("hello", 10, 50);
        f.add(p);
        f.pack();
        f.setVisible(true);
    }
    

    }



  • You have a code. p.getGraphics() returns null♪ The thing is, f.setVisible(true) After him. Nothing yet, getGraphics() I'll be back. null♪ Must be like that.

    private static void createAndShowGUI() {
        JPanel p = new JPanel();
        JFrame f = new JFrame("Swing PaintDemo");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    p.setOpaque(true);
    p.setBackground(Color.red);
    f.add(p);
    f.setVisible(true);
    f.pack();
    Graphics g = p.getGraphics();
    g.drawString("hello", 10, 50);
    

    }




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2