Java Reference
In-Depth Information
content.setLayout(new BorderLayout(20, 30));
Like the flow layout manager, you can also set the gaps individually by calling the methods setHgap()
and setVgap() for the BorderLayout object. For example:
BorderLayout border = new BorderLayout(); // Construct the object
content.setLayout(border); // Set the layout
border.setHgap(20); // Set horizontal gap
This sets the horizontal gap between the components to 20 pixels and leaves the vertical gap at the
default value of zero. You can also retrieve the current values for the gaps with the getHgap() and
getVgap() methods.
Using a Card Layout Manager
The card layout manager generates a stack of components, one on top of the other. The first component that
you add to the container will be at the top of the stack, and therefore visible, and the last one will be at the
bottom. You can create a CardLayout object with the default constructor, CardLayout() , or you can
specify horizontal and vertical gaps as arguments to the constructor. The gaps in this case are between the
edge of the component and the boundary of the container. We can see how this works in an applet:
Try It Out - Dealing Components
Because of the way a card layout works, we need a way to interact with the applet to switch from one
component to the next. We will implement this by enabling mouse events to be processed, but we won't
explain the code that does this in detail here. We will leave that to the next chapter.
Try the following code:
import javax.swing.JApplet;
import javax.swing.JButton;
import java.awt.Container;
import java.awt.CardLayout;
import java.awt.event.ActionEvent; // Classes to handle events
import java.awt.event.ActionListener;
public class TryCardLayout extends JApplet implements ActionListener {
CardLayout card = new CardLayout(50,50); // Create layout
public void init() {
Container content = getContentPane();
content.setLayout(card); // Set card as the layout mgr
JButton button; // Stores a button
for(int i = 1; i <= 6; i++) {
content.add(button = new JButton("Press " + i), "Card" + i); // Add a button
button.addActionListener(this); // Add listener for button
}
}
Search WWH ::




Custom Search