Tóm Tắt
What is the use of setBounds() method in Java?
The layout managers are used to automatically decide the position and size of the added components. In the absence of a layout manager, the position and size of the components have to be set manually. 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.
setBounds()
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); } }
Output
Advertisements