2017-04-19 146 views
0

我知道不推薦絕對定位,但我需要隨機散佈我的標籤以及隨機更改其位置。 我研究過如何使用setBounds,但它似乎不起作用。下面的代碼顯示了流佈局中的標籤,當我使用setLayout(null)時,它顯示一個空白幀。Java swing GUI絕對定位

public class GUI extends JFrame{ 

device mobiles[]; 
device station; 
JPanel pane= new JPanel(); 
public GUI() 
{ 
    setTitle("communication is Key"); 
    setSize(1000, 1000); 
    setResizable(false); 
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    pane.setBackground(Color.WHITE); 
    int x=0; int y=0; 
    mobiles= new device[10]; 
    for (int i = 0; i < 10; i++) { 
     x=randInt(); 
     y=randInt(); 
      mobiles[i]= new device(1,x,y); 
      pane.add(mobiles[i]); 

    } 
    x=randInt(); 
    y=randInt(); 
    station = new device(0,x,y); 
    pane.add(station); 

    this.add(pane); 
} 

,這是類 「設備」 是擴展JLabel

public class device extends JLabel{ 
ImageIcon mob = new ImageIcon("mob.png"); 
ImageIcon tow = new ImageIcon("tower.png"); 

public device(int num, int x, int y) 
{ if(num==1) 
    this.setIcon(mob); 
else this.setIcon(tow); 

this.setBounds(x, y, 3, 7); 
} 

}

在找出問題是什麼任何幫助,將不勝感激。

+0

*「但我需要證明我的標籤隨機分佈以及隨機改變自己的立場」 * - 有一個佈局管理器 - [例如](http://stackoverflow.com/questions/27974966/moving-jpasswordfield-to-absolute-position/27975101#27975101)和[示例](http://stackoverflow.com/examples/11819669/absolute-positioning-graphic-jpanel-inside-jframe-blocked-by-blank-sections/11822601)#11822601) – MadProgrammer

+0

[Example](http://stackoverflow.com/questions/17847816/position-image-在任何屏幕分辨率/ 17848635#17848635) – MadProgrammer

回答

1

下面的代碼顯示了流佈局中的標籤,當我使用setLayout(null)時,它顯示一個空白幀。

佈局管理器設置組件的大小和位置。

如果您不使用佈局管理器,那麼您需要負責設置每個組件的sizelocation

通常我會設置大小等於組件preferred size

另外,您是否顯示隨機生成的x/y值?也許值大於面板的大小。

當我使用setLayout(null)時,它顯示一個空白幀。

什麼佈局設置爲空?框架的面板。您的代碼不使用上述方法。發佈您用來解決問題的代碼。我們不想猜測你可能做什麼,也可能沒有做什麼。

+0

我試過pane.setLayout(null )和/或this.setLayout(null)...仍然播種一個空框架。隨機函數由幀大小範圍內的最小值和最大值設置。 – MNS

+0

@MNS,'並且隨機函數在幀大小範圍內由最小值和最大值設置 - 其中是執行該操作的代碼。在你的回答中再次提及我的評論。除非您實際發佈您使用的代碼,否則我們無法確定您所做的是否正確。不要讓我們猜測! – camickr

0

感謝@CasparNoree ...答案建議是,從一開始初始化Japnel:

JPanel pane = new JPanel(null); 
+0

嗯,是的,佈局需要設置之前,你添加組件到面板。這就是爲什麼我建議您在發佈代碼時發佈實際測試的代碼。我們需要看看你在做什麼,而不是你說的是什麼,因爲很多時候口頭描述並不能準確地反映你的真實代碼。 – camickr