How can we used setBounds() method? Explain its use with suitable program code.
setBounds()
The setBounds() method is used in such a situation to set the position and size. To specify the position and size of the components manually, the layout manager of the frame can be null.
The setBounds() method needs four arguments. The first two arguments are x and y coordinates of the top-left corner of the component, the third argument is the width of the component and the fourth argument is the height of the component.
Syntax
setBounds(int x-coordinate, int y-coordinate, int width, int height)
Example
import javax.swing.*;
import java.awt.*;
public class SetBoundsTest {
public static void main(String arg[]) {
JFrame frame = new JFrame("SetBounds Method Test");
frame.setSize(375, 250);
// Setting layout as null
frame.setLayout(null);
// Creating Button
JButton button = new JButton("Hello Java");
// Setting position and size of a button
button.setBounds(80,30,120,40);
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
Comments
Post a Comment