![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to set the location of a button anywhere in JFrame?
To set location of a button anywhere a JFrame, use the setBounds() method. Let us first create a frame and a panel −
JFrame frame = new JFrame("Demo Frame"); JPanel panel = new JPanel(); frame.getContentPane();
Create a component i.e. label and set the dimensions using setBounds(). Here, you can set the location in the form of x and y coordinates and place the button anywhere in a frame −
JButton button = new JButton("Demo Button"); Dimension size = button.getPreferredSize(); button.setBounds(300, 180, size.width, size.height);
The following is an example to set the location of a button anywhere in JFrame −
Example
package my; import java.awt.Dimension; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.WindowConstants; public class SwingDemo { public static void main(String[] args) { JFrame frame = new JFrame("Demo Frame"); JPanel panel = new JPanel(); frame.getContentPane(); JButton button = new JButton("Demo Button"); Dimension size = button.getPreferredSize(); button.setBounds(300, 180, size.width, size.height); panel.setLayout(null); panel.add(button); panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.add(panel); frame.setSize(500, 300); frame.setVisible(true); } }
Output
Advertisements