0

I am trying to draw something using paint() on my JFrame. I can't get it to show though. Why?

claass DrawOn extends JFrame{
   public static void main(String args[]){
     new DrawOn();
   } 

   public DrawOn(){
     setVisible(true);
     pack();
    }

   paint(Graphics g){
     g.drawOval(10,10,100,100);
   }
}
  • Possible duplicate of: http://stackoverflow.com/questions/13404398/using-paintcomponent-to-draw-rectangle-in-jframe – BitNinja Feb 23 '14 at 20:47
  • Read the section from the Swing tutorial on [Custom Painting](http://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) for working examples and explanations on how painting works. – camickr Feb 23 '14 at 21:15

1 Answers1

0

You should draw in a JPanel:

JPanel panel = new JPanel()
{
    @Override
    protected void paintComponent(Graphics g)
    {
        // TODO Auto-generated method stub
        super.paintComponent(g);
        g.drawOval(10, 10, 100, 100);
    }
};

Don't forget to add the JPanel to the JFrame:

add(panel);

Code:

public DrawOn()
{

    JPanel panel = new JPanel()
    {
        @Override
        protected void paintComponent(Graphics g)
        {
            // TODO Auto-generated method stub
            super.paintComponent(g);
            g.drawOval(10, 10, 100, 100);
        }
    };

    add(panel);
    setPreferredSize(new Dimension(200, 200));
    setVisible(true);
    pack();
}

Note: You could make a class that extends JPanel instead of using an anonymous class so your code is clearer.

Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
  • Don't use setPreferredSize(). Override the getPreferredSize() method of the custom panel as demonstrated in the Swing tutorial. – camickr Feb 23 '14 at 21:22
  • @camickr Why? Could you provide a link to that part of the tutorial? – Christian Tapia Feb 23 '14 at 21:25
  • Don't know about the tutorial, but see [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) – Andrew Thompson Feb 23 '14 at 23:17
  • 1
    Andrew provided you with a link regarding the general usage of those methods. My comment was more direct regarding how custom painting should be done. It is the responsibility of the component to return a reasonable value for the preferred size of a component when doing custom painting. Your suggestion only happens to work because the component is added to the center of a BorderLayout. Try adding the component to the NORTH, SOUTH, WEST, or EAST or a panel using the FlowLayout and the component will not appear because the preferred size needs to be non-zero. Take a look at "step 2". – camickr Feb 24 '14 at 00:15