的构造很简单,一旦你了解它。请务必将类构造函数命名为与您的类相同的名称。通常,你想创建私有变量来分配构造函数的输入。在这种情况下,我们创建了私有的int x,y,w和h,以在我们的构造函数中分配输入的int x,int y,int w和int h。在绘制时,我们就在Graphics2D对象把我们需要的形状,点等
public class className{
//Creating object properties
private int x, y, w, h;
//Class Constructor
public className(int x, int y, int w, int h){
this.x = x;
this.y = y;
this.w = w;
this.h = h;
}
//For drawing, you want to take in a Graphics2D Object (g2)
public void draw(Graphics2D g2){
g2.drawOval(x, y, w, h);
}
}
在主类或任何你的paintComponent是,使用你的构造你键入:
className objectName = new className(100, 200, 300, 400);
该代码创建一个名为“objectName”的名称为“objectName”的新对象,其中x为100,y为200,w,300,h为400.要调用绘图函数,只需键入:
objectName.draw(g2); //Where g2 is some Graphics2D object
在你的情况下会有什么'g'?既然你已经发现了一些代码/知识,为什么你没有彻底阅读它? 'g.drawOval(x,y,w,h);'属于组件的(可能是面板)'paint(Graphics g)'方法。 – Thomas
@Thomas我认为你的意思是'paintComponent(Graphics g)'方法,而不是'paint'一个... – Frakcool
@Frakcool你可以重写它们,但是'paintComponent(...)'可能是更好的。 :) – Thomas