Scorpion
Scorpion

Reputation: 587

Drawing oval using drawOval() method

At first I wrote this class DrawOval.java as follows :-

public class DrawOval extends JPanel{
    private int diameter = 10;

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.fillOval(10,10,diameter,diameter);
    }
    public void setDiameter(int newD){
        diameter = (newD>=0 ? newD : 10);
        repaint();
    }
    public Dimension getPreferredSize(){
        return new Dimension(200,200);
    }
    public Dimension getMinimumSize(){
        return getPreferredSize();
    }
}

then I wrote this class TheWindow.java as follows :-

public class TheWindow extends JFrame{
    private DrawOval myPanel;
    public TheWindow(){
        super("The title");
        myPanel = new DrawOval();
        myPanel.setBackground(Color.GREEN);
        add(myPanel,BorderLayout.CENTER);
    }
}

At last I wrote the main class as follows:-

public class Test{
    public static void main(String[] args){
        TheWindow w = new TheWindow();
        w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        w.setSize(300,300);
        w.setVisible(true);
    }
}

and the output is only a frame with a green background without any oval ?

Upvotes: 1

Views: 1874

Answers (2)

Anastasios Vlasopoulos
Anastasios Vlasopoulos

Reputation: 1802

You should call setDiameter method in order the oval shape to be drawn. But i think you should merge this method with the paintComponent. By this way you should not care about calling the method.

What i mean is:

public void paintComponent(Graphics g, int newD){

    super.paintComponent(g);

    diameter = (newD>=0 ? newD : 10);
    repaint();          

    g.fillOval(10,10,diameter,diameter);

}

Upvotes: 0

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

You never call setDiameter(...) and so the field holds a 0 value and no oval will be drawn.

One solution is to try to remember to call this method every time you create a DrawOval object, but why force yourself to remember this? Instead make diameter a parameter of the constructor and make sure that the class has no default constructor so that it the diameter field must be set to some value on object creation. Another option is to give the diameter field a default value, so that even if it is never set explicitly, it will always be set implicitly.

Upvotes: 1

Related Questions