2017-10-09 30 views
0

我想創建一個項目,我有一個構造函數,構造帶有x,y,寬度,高度的圓,然後使用Jpanel繪製它們。 Unfortunatley我有沒有運氣試圖自己或找到任何像樣的資源...爲JPanel創建構造函數來創建圈子?

有人可以幫我嗎?謝謝.. 我想待辦事項這樣的

public Circle(int x , int y, int w, int h) { 
    g.drawOval(x,y,w,h); 
} 

而且,我想知道是否有任何比JPanel的更好的方法? 我正在構建一個應用程序,它可以生成兩個圓並移動,檢測它們相交的時間並標記相交區域。

+0

在你的情況下會有什麼'g'?既然你已經發現了一些代碼/知識,爲什麼你沒有徹底閱讀它? 'g.drawOval(x,y,w,h);'屬於組件的(可能是面板)'paint(Graphics g)'方法。 – Thomas

+0

@Thomas我認爲你的意思是'paintComponent(Graphics g)'方法,而不是'paint'一個... – Frakcool

+0

@Frakcool你可以重寫它們,但是'paintComponent(...)'可能是更好的。 :) – Thomas

回答

2

看起來你正在嘗試使用Graphics類進行繪製。

你會想是這樣的:

public class Circle { 
public int x,y,w,h; 
public Circle(int xx,yy,ww,hh) { 
    x = xx; 
    y = yy; 
    w = ww; 
    h = hh; 
} 
public int getX() { 
    return x; 
} 
public int getY() { 
    return y; 
} 
public int getW() { 
    return w; 
} 
public int getH() { 
    return h; 
} 
} 
class MainClass { 
public circle = new Circle(50,50,50,50); 
@Override 
public void paintComponent(Graphics g) { 
    g.drawOval(circle.getX(),circle.getY(),circle.getW(),circle.getH()); 
} 
0

的構造很簡單,一旦你瞭解它。請務必將類構造函數命名爲與您的類相同的名稱。通常,你想創建私有變量來分配構造函數的輸入。在這種情況下,我們創建了私有的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