2017-04-19 76 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