我知道我是一個白癡,這就是爲什麼我無法弄清楚,但我試圖用paintComponent繪製一堆具有隨機大小和位置的矩形。我試圖確保他們都被畫在框架內。我可以用下面的代碼(代碼片段)完成它,但我想知道是否有更好的方法來完成它,而不是將數字硬編碼到程序中。有沒有一種方法可以讓我看看這可能是我正在尋找的?在JFrame中保留矩形
這裏的內部類,它覆蓋的paintComponent()方法:
class DrawPanel extends JPanel {
public void paintComponent(Graphics g) {
int red = (int)(Math.random()*256);
int blue = (int)(Math.random()*256);
int green = (int)(Math.random()*256);
g.setColor(new Color(red, blue, green));
//The following 4 lines keep the rects within the frame
//The frame is 500,500
int ht = (int)(Math.random()*400);
int wd = (int)(Math.random()*400);
int x = (int)(Math.random()*100);
int y = (int)(Math.random()*100);
g.fillRect(x,y,ht,wd);
}
}
您遇到了什麼問題?你確定你想在'paintComponent(...)'中隨機化,這樣任何時候GUI因任何原因被重新繪製時,矩形將會改變。你確定你不想調用'super.paintComponent(...)'方法嗎? –
另外,你不應該使用DrawPanel的'getSize()'而不使用JFrame的大小嗎?否則你忽略了它的標題欄等... –
看到相關的例子[這裏](http://stackoverflow.com/q/9849950/230513)。 – trashgod