2012-07-31 116 views
9

我需要創建一個矩形對象,然後使用paint()將其繪製到applet。我試圖如何使用g.fillRect方法在Java中創建Rectangle對象

Rectangle r = new Rectangle(arg,arg1,arg2,arg3); 

然後嘗試使用

g.draw(r); 

它沒有工作給它畫的小程序。有沒有辦法在Java中做到這一點?我已經搜索了谷歌在其生命的一英寸內尋找答案,但我一直無法找到答案。請幫忙!

回答

14

試試這個:

public void paint (Graphics g) {  
    Rectangle r = new Rectangle(xPos,yPos,width,height); 
    g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight()); 
} 
+0

簡潔準確 – 2014-10-09 15:40:47

5

你可以試試這樣:

import java.applet.Applet; 
import java.awt.*; 

public class Rect1 extends Applet { 

    public void paint (Graphics g) { 
    g.drawRect (x, y, width, height); //can use either of the two// 
    g.fillRect (x, y, width, height); 
    g.setColor(color); 
    } 

} 

其中x是x座標 y是ÿcordinate 顏色=你想使用如Color.blue

的顏色,如果你想使用矩形對象,你可以做這樣的:

import java.applet.Applet; 
import java.awt.*; 

public class Rect1 extends Applet { 

    public void paint (Graphics g) {  
    Rectangle r = new Rectangle(arg,arg1,arg2,arg3); 
    g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight()); 
    g.setColor(color); 
    } 
}  
+2

如果您必須使用矩形對象,那麼只需輸入: g.drawRect(r.getX(),r.getY(),r.getWidth(),r.getHeight()); – 2012-07-31 17:31:59

相關問題