- Trending Categories
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
- Related Articles
- How to set location of JLabel in a JFrame with Java?
- How to set default button for JFrame in Java?
- How to close JFrame on the click of a Button in Java
- How to disable close button on a JFrame in Java?
- How can we disable the maximize button of a JFrame in Java?
- How to set FlowLayout for JFrame in Java?
- How to set minimum size limit for a JFrame in Java
- How to use the Set-Location command in PowerShell?
- How to set the location of the Tabs in a JTabbedPane Container to the left in Java?
- Set the location of component in a GridBagLayout with Java
- How can I set the location of minor ticks in Matplotlib?
- How to display a JFrame to the center of a screen in Java?
- How to set OnclickListener on a radio button in android?
- How to set the sticky button property properly?
- How to set location and location.href using JavaScript?

Advertisements