简体   繁体   中英

JAVA How to resize a JFrame during run time?

How do I resize a JFrame from outside the constructor and with a static method ?

Let me explain why I need this.

I'm programming a Zelda-like game in Java, and I have a dungeon. In my dungeon, there're normal-sized rooms, and the boss room. So my question is, is it possible to resize my JFrame later on the game since the Boss room's dimensions are different from the others' ? I'm drawing directly on the JFrame .

I tried using setSize(int,int) , but it can only be used as non-static .

Please, let me know if what I ask is not clear.

Thank you for reading

How do I resize a JFrame from outside the constructor and with a static method ?

  • create JFrame as local variable, don't to extends JFrame

So my question is, is it possible to resize my JFrame later on the game since the Boss room's dimensions are different from the others' ?

  • yes, I'd be preffer JFrame.pack(then its childs returns proper PreferredSize and laid by proper LayoutManager), over setSize(int, int) or setPreferredSize(new Dimension(int, int)) and with JFrame.pack(), all mentioned three choices works on runtime in all cases

I'm drawing directly on the JFrame.

  • this is wrong decision, use JPanel for painting, override JPanels getPreferredSize for JFrame.pack() then all coordinates for JFrame and for custom paiting are calculated based on getPreferredSize

I tried using setSize(int,int), but it can only be used as non-static.

  • no idea without an SSCCE

If you want to use setSize(int,int) in static context you should do something like this

public class Main {

    static JFrame f;

    public static void main(String args[]) {
        f = new JFrame();
        f.add(new JLabel("prova"));
        f.setVisible(true);
        f.setSize(900, 900);
    }
}

by declaring the JFrame as static you can call setSize in both static and non-static context.

If you are trying to do to do

public class MyFrame extends JFrame() {

    public static void changeSize(int a, int b) {
        setSize(a,b);
    }

    ....
}

this can't be done because static methods can't refer to non-static objects (such as the current instance of the class MyFrame. Static methods can access only static objects like

public class MyFrame extends JFrame() {

    static int l;

    public static void changeSize(int a, int b) {
        l = 10;
    }

    ....
}

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