How to tell a JDesktopPane to fill the entire screen of JFrame

657 Views Asked by At

Any body please suggest the code How to tell a JDesktopPane to fill the entire screen of JFrame in Java Netbeans IDE.

1

There are 1 best solutions below

2
STaefi On
  1. Set the layout of your JFrame to BorderLayout.
  2. Add your JDesktopPane to the CENTER area of your JFrame:

    JFrame f = new JFrame();
    f.setBounds(50, 50, 500, 400);
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.setLayout(new BorderLayout());
    JDesktopPane desktopPane = new JDesktopPane();
    f.add(desktopPane, BorderLayout.CENTER);        
    f.setVisible(true);
    

The magic is coming from how BorderLayout manages the layout of its children components. Anything is added to the CENTER area of BorderLayout will fill as much area as it can get from the its container.

If you want to maximize a JInternalFrame inside the JDesktopPane, you should call setMaximum(true) on it after it's added to the underlying JDesktopPane:

public class JDesktop {

    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setBounds(50, 50, 500, 400);
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.setLayout(new BorderLayout());

        JInternalFrame internalFrame1 = new JInternalFrame("Internal Frame 1", true, true, true, true);     
        internalFrame1.setSize(150, 150);
        internalFrame1.setVisible(true);        

        JDesktopPane desktopPane = new JDesktopPane();
        desktopPane.add(internalFrame1);
        try {
            internalFrame1.setMaximum(true);
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
        f.add(desktopPane, BorderLayout.CENTER);
        f.setVisible(true);
    }
} 

Now that you got the idea it's not bad to know about the defaults. The default layout manager for JFrame is BorderLayout and when you add anything to a JFrame without specifying the constraint for the area, it will be added to the CENTER area. So you can omit these lines in you code:

f.setLayout(new BorderLayout());

and you can add the desktopPane simply using this line:

f.add(desktopPane);