Java swing GUI absolute positioning

MNS picture MNS · Apr 19, 2017 · Viewed 9.8k times · Source

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);
}

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.

Answer

camickr picture camickr · Apr 19, 2017

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.

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.

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

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.