简体   繁体   中英

Resizing JFrame from JPanel

I'm curious is there a way to resize window from JPanel object. I'm looking for solution for a while. Maybe I'm missing something?

I want to resize window when use changeSize() method (fe on button, I deleted lot code).

I've tried different methods like setSize , setPreferredSize and setBorders .

public class MAIN{
    public static void main(String[] args) {
         new Okno(new Panel_Saper());
    }
}

public class Okno extends JFrame{
    protected Okno(Panel panel) {
        setResizable(true);
        getContentPane();
        Container cp = getContentPane();
        cp.add(panel);
        pack();
        setDefaultCloseOperation(panel.getClose());//2 - JFrame.DISPOSE_ON_CLOSE, 3 - JFrame.EXIT_ON_CLOSE
        setVisible(true);
    }
}

public abstract class Panel extends JPanel {
    protected int getClose() {return 2;} //2 - JFrame.DISPOSE_ON_CLOSE
}//needed for override in other place

public class Panel_Saper extends Panel {
    Panel_Saper() {
        setLayout(null);
        setPreferredSize(new Dimension(400,400));   
    }

    public void changeSize() {//DOESN'T WORK
        SetSize(new Dimension(600,600));
        setBounds(0, 0, 600, 600);
        repaint();
    }
}

For your custom panel it is preferred that you override the getPreferredSize() method. Every Swing component is responsible for knowing its preferred size.

If you want to change the preferred size from 400 to 600 you must have a reason for doing this. So you should have a property for your panel that you can modify.

Then your implementation of the getPreferredSize() method will check this property and return the appropriate size depending on the current state of your panel.

I made work around by closing and reopening window

Now that your component has implemented the getPreferredSize() correctly you can simple invoke pack() on the JFrame.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM