How can I place an object in a specific location (x,y) on a JFrame?
Here find the Absolute Positioning Tutorials. Please do read carefully, as to why this approach is discouraged over using LayoutManagers
To add say a JButton to your JPanel, you can use this :
JButton button = new JButton("Click Me");
button.setBounds(5, 5, 50, 30);
panel.add(button);
Here try this example program :
import java.awt.*;
import javax.swing.*;
public class AbsoluteLayoutExample
{
private void displayGUI()
{
JFrame frame = new JFrame("Absolute Layout Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setOpaque(true);
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(null);
JLabel label = new JLabel(
"This JPanel uses Absolute Positioning"
, JLabel.CENTER);
label.setSize(300, 30);
label.setLocation(5, 5);
JButton button = new JButton("USELESS");
button.setSize(100, 30);
button.setLocation(95, 45);
contentPane.add(label);
contentPane.add(button);
frame.setContentPane(contentPane);
frame.setSize(310, 125);
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new AbsoluteLayoutExample().displayGUI();
}
});
}
}
Try these 2... in combination with each other...
setLocation()
and setBounds()
Its even better to use GroupLayout, developed by NetBeans team in 2005. WindowsBuilder Pro is a good tool for Building Gui in java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With