Search code examples
javaswinglayoutawt

How do set position of JPanel anywhere on screen


I need to have a number of JPanels, and I cannot position them where I want to as they either disappear as I try and change things like boundaries for example. Any help is appreciated

Here is the code for my panel I am trying to position. I want it on the right hand side about 3/4 of the way down the screen but I cant get it out of the top right corner

textField = new JTextField("Sample Text");
textField.setPreferredSize(new Dimension(200, 30));
textField.setFont(new Font("Arial", Font.PLAIN, 16));
textField.setEditable(false); // Set to false to make it read-only

JPanel textPanel = new JPanel(new GridBagLayout());
textPanel.add(textField);
add(textPanel, BorderLayout.NORTH);

Solution

  • Panels (and all Swing components) will always require a top level component like JFrame, JDialog or JWindow to be rendered on the screen. Even if you position the panel absolute within the top level container (and the layout manager's job is to correct that mistake) - it is the top level container's position that you need to change.

    Here an example that creates a window not in the top left corner:

    import javax.swing.JFrame;
    import javax.swing.JLabel;
    
    public class Main {
        
        public static void main(String[] args) {
            JFrame f = new JFrame("Positioning Test Frame");
            f.add(new JLabel("Window Content Area"));
            f.pack(); // make the Window as small as possible
            //f.setLocationRelativeTo(null); // this line will center the window
            f.setLocation(200, 200); // this line will go to absolute coordinates
            f.setVisible(true);
        }
    }
    

    You may need to compute your window position (at the right hand side about 3/4 of the way down) based on the screen size. Here is code that will deliver the desktop size (which may consist of multiple screens). If you are interested in only one of the screens you can probably see where to get that value.

    public static Rectangle2D getDesktopSize() {
        Rectangle2D result = new Rectangle2D.Double();
        GraphicsEnvironment localGE = GraphicsEnvironment.getLocalGraphicsEnvironment();
        for (GraphicsDevice gd : localGE.getScreenDevices()) {
          for (GraphicsConfiguration graphicsConfiguration : gd.getConfigurations()) {
            result.union(result, graphicsConfiguration.getBounds(), result);
          }
        }
        return result;
    }