Java Swing GUI绝对定位 [英] Java swing GUI absolute positioning

查看:31
本文介绍了Java Swing GUI绝对定位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道不推荐使用绝对定位,但我需要显示随机分散的标签以及随机改变它们的位置.我研究了如何使用 setBounds 但它似乎不起作用.以下代码显示了 Flow Layout 中的标签,当我使用 setLayout(null) 时,它显示一个空白框架.

I know that absolute positioning is not recommended, but I need to show my labels randomly scattered as well as randomly changing their positions. I have researched how to use setBounds but it doesn't seem to work. The following code shows the labels in a Flow Layout, and when I use setLayout(null) it shows a blank frame.

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 的类设备"

and this is class "devices" that extends 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);
}

}

任何帮助找出问题所在,我们将不胜感激.

any help in finding out what the problem is, would be be appreciated.

推荐答案

以下代码显示 Flow Layout 中的标签,当我使用 setLayout(null) 时,它显示一个空白框架.

The following code shows the labels in a Flow Layout, and when I use setLayout(null) it shows a blank frame.

布局管理器设置组件的大小和位置.

The layout manager sets the size and location of the component.

如果你不使用布局管理器,那么你负责设置每个组件的sizelocation.

If you don't use the layout manager, then you are responsible for set the size and location of each component.

通常我会将大小设置为等于组件首选大小.

Typically I would set the size to equal to the components preferred size.

另外,您是否显示了随机生成的 x/y 值?也许这些值大于面板的大小.

Also, did you display the x/y value that are randomly generated? Maybe the values are larger than the size of the panel.

当我使用 setLayout(null) 时,它显示一个空白框架.

and when I use setLayout(null) it shows a blank frame.

什么布局设置为空?框架的面板.您的代码未使用上述方法.发布用于导致问题的代码.我们不想猜测您可能会或可能不会做什么.

What layout is set to null? The panel of the frame. Your code doesn't use the above method. Post the code that you use to cause the problem. We don't want to guess what you may or may not be doing.

这篇关于Java Swing GUI绝对定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆