2010-05-26 4 views

답변

1

java.util.RandomnextInt(int)과 함께 JFrame.setLocation(int, int)을 사용하십시오. 예를 들어

,

frame.setLocation(random.nextInt(500), random.nextInt(500)); 
+2

및 GraphicsEnvironment/GraphicsDevice를 사용하여 화면 크기를 가져옵니다. –

3

는 새 위치에 JFrame를 찾습니다 setLocation(int, int)JFrame의를 사용할 수 있습니다.

따라서 이것을 프레임 생성자에 넣고 Random을 사용하여 임의의 위치를 ​​생성하면 프레임이 매번 임의의 위치에 나타납니다.

또 다른 옵션은 JFrame의 setVisible(boolean) 메서드를 재정의하는 것입니다.

public void setVisible(boolean visible){ 
    super.setVisible(visible); 
    if (visible) { 
     Random r = new Random(); 
     // Find the screen size 
     Toolkit tk = Toolkit.getDefaultToolkit(); 
     Dimension d = tk.getScreenSize(); 
     // randomize new location taking into account 
     // the screen size, and current size of the window 
     int x = r.nextInt(d.x - getWidth()); 
     int y = r.nextInt(d.y - getHeight()); 
     setLocation(x, y); 
    } 
} 

블록 내에있는 코드는 생성자 내에서 이동할 수 있습니다. getWidth()getHieght() 메서드는 예상 한 올바른 값을 반환하지 않을 수 있습니다.

관련 문제