简体   繁体   English

使用drawOval()方法绘制椭圆

[英]Drawing oval using drawOval() method

At first I wrote this class DrawOval.java as follows :- 首先,我编写了如下类DrawOval.java:

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 :- 然后我按如下方式编写此类TheWindow.java:

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 ? 并且输出仅是具有绿色背景且没有任何椭圆形的帧?

You never call setDiameter(...) and so the field holds a 0 value and no oval will be drawn. 您永远不会调用setDiameter(...) ,因此该字段的值为0,并且不会绘制任何椭圆形。

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? 一种解决方案是尝试记住每次创建DrawOval对象时都调用此方法,但是为什么要强迫自己记住这一点呢? 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. 另一个选择是给直径字段一个默认值,这样即使从不显式设置它,也总是隐式设置。

You should call setDiameter method in order the oval shape to be drawn. 您应该调用setDiameter方法以绘制椭圆形。 But i think you should merge this method with the paintComponent. 但是我认为您应该将此方法与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);

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM