PDA

Click to See Complete Forum and Search --> : component location problem


Linette
Jun 5th, 2002, 07:42 PM
hi,
i'm wondering if there's any way to control where your components are placed, on an applet, when you're using no particular layout manager..
i heard you could, with some method involving the statement setLayout(null); but i don't know what else i'm supposed to do with that, cuz that alone doesn't do anything.. can anyone help me?

thanks!

linette

Dillinger4
Jun 6th, 2002, 12:47 AM
If you set the layout manager to null you would have to use absoulte positioning. Once the layout manager is set to null there are multiple ways you could position your component. You could use any of the following methods depending on your needs. setLocation(Point p), setLocation(int x,int y), setBounds(int x, int y, int width, int height), setBounds(Rectangle r). Using this approach can get quite complicate though and as far as sun says shouldn't be done due to how other platforms might render you components.

Here is an example that i whipped up which uses absoulte positioning.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;


public class Layout{
public static void main(String [] args){

int height = 50;
int width = 50;
int space = 10;
int x = 0;
int y = 10;
JFrame jf = new JFrame("Layout Example");

Container c = jf.getContentPane();
c.setLayout(null);
jf.addWindowListener(new WindowMonitor());
jf.setSize(700,400);
jf.setResizable(false);
jf.setVisible(true);

JButton[] jb = new JButton[54];
for(int i = 0; i < jb.length; ++i){
jb[i] = new JButton(new Integer(i).toString());
jb[i].setSize(width, height);

}
for(int i = 0; i < jb.length; ++i){

if(x == 0){
x = 10;
jb[i].setBounds(new Rectangle(x, y, width, height));
c.add(jb[i]);
continue;
}
x += (width + space);
jb[i].setBounds(new Rectangle(x, y, width, height));
c.add(jb[i]);

if(x > (jf.getWidth() - (width + space))){
x = 10;
y += (height + space);
jb[i].setBounds(new Rectangle(x, y, width, height));
c.add(jb[i]);
}
}
}
}

class WindowMonitor extends WindowAdapter {
public void windowClosing(WindowEvent we){
System.exit(0);
}
}

Linette
Jun 6th, 2002, 01:27 PM
thanks!

Dillinger4
Jun 7th, 2002, 11:00 PM
No problem. More than happy. :)