1
代碼:如何在隨機座標上繪製一個隨機大小的圓,以便該圓完全可見?
Random rand = new Random();
JPanel mainPanel;
int randomSize = 0;
int randomPositionX = 0;
int randomPositionY = 0;
final static int FRAME_HEIGHT = 500;
final static int FRAME_WIDTH = 500;
final static int TITLE_BAR = 30 ;
final static int MAX_SIZE = 100;
final static int MIN_SIZE = 10 ;
/* All the below code is put into a method */
mainPanel = new JPanel(){
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(randomPositionY, randomPositionX, randomSize, randomSize);
}
};
do{
randomSize = rand.nextInt(MAX_SIZE) + 1;
}while(randomSize < MIN_SIZE);
do{
randomPositionX = rand.nextInt(FRAME_WIDTH);
randomPositionY = rand.nextInt(FRAME_HEIGHT);
}while((randomPositionX + randomSize > FRAME_WIDTH) || (randomPositionY + randomSize > FRAME_HEIGHT - TITLE_BAR));
repaint();
我想要的是具有隨機的尺寸,使得它應該有10的最小尺寸和圓也應該在隨機畫協調這種爲100的最大尺寸的圓在JPanel mainPanel
內的圈子是完全可見的。
請注意,mainPanel
將被添加到大小設置爲setSize(FRAME_WIDTH, FRAME_HEIGHT);
的JFrame中。
但問題是,有時,在圓的一部分是成功的一半外一半的JPanel的內:
哪兒我去錯了嗎?
那麼,我該如何解決這些問題呢? –
@CoolGuy放棄所有框架引用並關注組件的實際大小 – MadProgrammer