The setLayout() method is used to specify a container’s layout.
In Core Java, the method used to specify a container’s layout is the setLayout
method. This method is part of the Container
class, which is a superclass of components like JPanel
, JFrame
, etc., in Java’s Swing framework.
Here’s a simple example of how you might use setLayout
:
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.FlowLayout;
public class ExampleFrame extends JFrame {
public ExampleFrame() {
// Set the layout for the frame
setLayout(new FlowLayout());
// Add some components to the frame
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
add(button1);
add(button2);
// Set frame properties
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new ExampleFrame();
}
}
In this example, setLayout(new FlowLayout())
sets the layout of the ExampleFrame
to a FlowLayout
, but you can use other layout managers like BorderLayout
, GridLayout
, etc., depending on your specific layout requirements.