Java Reference
In-Depth Information
Q&A
Q I really dislike working with layout managers; they're either too simplistic or
too complicated (the grid bag layout, for example). Even with a lot of tinker-
ing, I can never get my user interface to look like I want it to. All I want to do
is define the sizes of my components and put them at an x,y position on the
screen. Can I do this?
A It's possible but problematic. Java was designed in such a way that a program's
graphical user interface could run equally well on different platforms and with dif-
ferent screen resolutions, fonts, screen sizes, and the like. Relying on pixel coordi-
nates can cause a program that looks good on one platform to be unusable on
others, where layout disasters such as components overlapping each other or get-
ting cut off by the edge of a container may result. Layout managers, by dynami-
cally placing elements on the screen, get around these problems. Although there
might be some differences among the end results on different platforms, the differ-
ences are less likely to be catastrophic.
If none of that is persuasive, here's how to ignore my advice: Set the content
pane's layout manager with null as the argument, create a Rectangle object (from
the java.awt package) with the x,y position, width, and height of the component
as arguments, and then call the component's setBounds(Rectangle) method with
that rectangle as the argument.
The following application displays a 300-by-300 pixel frame with a Click Me but-
ton at the (x,y) position 10, 10 that is 120 pixels wide by 30 pixels tall:
import java.awt.*;
import javax.swing.*;
public class Absolute extends JFrame {
public Absolute() {
super(“Example”);
setSize(300, 300);
Container pane = getContentPane();
pane.setLayout(null);
JButton myButton = new JButton(“Click Me”);
myButton.setBounds(new Rectangle(10, 10, 120, 30));
pane.add(myButton);
setContentPane(pane);
setVisible(true);
}
public static void main(String[] arguments) {
Absolute ex = new Absolute();
}
}
You can find out more about setBounds() in the Component class. The documenta-
tion for the Java class library can be found on the Web at http://java.sun.com/
javase/6/docs/api.
 
Search WWH ::




Custom Search