White bars in the right and bottom sides of a canv

2020-05-05 17:20发布

问题:

So guys, using a JOptionPane to ask the user if the app should update or not, and after which I get these white bars in the bottom and right sides of my canvas. Tried removing the autoupdate thing and works fine. Here's my code

GameUtils.init();
String version = AutoUpdate.checkForUpdates();
if (Double.parseDouble(version) > AutoUpdate.VERSION) {
    AutoUpdate.update(version);            
    JFrame frame = null;

    try
    {
        frame = new JFrame(GameUtils.data.getString("title"));
    } catch (JSONException e)
    {
        e.printStackTrace();
    }

    frame.getContentPane().setPreferredSize(new Dimension(1000, 500));
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    frame.setResizable(false);
    frame.pack();
    frame.setLocationRelativeTo(null);
    GameUtils.instance = new Game(frame);

    frame.addWindowListener(new WindowListener() {
        @Override
        public void windowOpened(WindowEvent e) {

        }

        @Override
        public void windowClosing(WindowEvent e) {
            GameUtils.instance.stop();
            System.exit(0);
        }

        @Override
        public void windowClosed(WindowEvent e) {


        }

        @Override
        public void windowIconified(WindowEvent e) {

        }

        @Override
        public void windowDeiconified(WindowEvent e) {

        }

        @Override
        public void windowActivated(WindowEvent e) {

        }

        @Override
        public void windowDeactivated(WindowEvent e) {

        }
    });
    frame.setVisible(true);
    GameUtils.instance.start();
}

Coordinating system works normally I want it to look this way

回答1:

I have the same problem you noticed when i use setResizable(false) and pack() method in a JFrame. Here you can find an answer which describes the problem, but i didn't find a solution that works for me.

In my applications i use a sort of "trick" if needed: i check if the contentPane preferred width is equal to his effective width, if not i recall pack() method.

Something like:

for(int i=0;i<5 && contentPane.getPreferredSize().width!=contentPane.getSize().width;i++) frame.pack();

Of course this isn't a really good solution, but it works for me and if you use a parameter to limit the maximum number of times that pack() should occur, you don't risk to block your gui...