开发者

Problem - Container changing size automatically in Java

开发者 https://www.devze.com 2022-12-18 08:54 出处:网络
I\'ve found that my container is actually changing it\'s size a short while after being constructed When it\'s constructed, I set my components to be at the place I want (like 30px away from the righ

I've found that my container is actually changing it's size a short while after being constructed

When it's constructed, I set my components to be at the place I want (like 30px away from the right edge) but later after a short while, I find that it turns from 1008x730 to 1018x740...

(My JFrame is 1024x768)

Does anyone know why this happens and how I can stop this auto-resizing thing?

Thank you.

I just did a -

while (true) {
        System.out.println(c.getSize());
}

And the size chang开发者_如何学JAVAed after a few iterations.

~Edited


It sounds like you're doing something that changes a component's size and revalidates after calling pack() on the JFrame. Also, rather than calling setSize(), it's often better to set a component's preferred size and let the LayoutManager arrange things.

Addendum: It's generally better to invoke pack() on a top-level container in order to get the initial sizes correct. Also, the content pane of a JFrame defaults to BorderLayout, which may not be what you want.

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class MyPanel extends JPanel {

    public MyPanel() {
        this.setLayout(new GridLayout(2, 2));
        this.setPreferredSize(new Dimension(320, 240));
        for (int i = 0; i < 4; i++) {
            JLabel label = new JLabel(String.valueOf(i));
            label.setHorizontalAlignment(JLabel.CENTER);
            label.setBorder(BorderFactory.createLineBorder(Color.blue));
            this.add(label);
        }

    }

    private static void create() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(new MyPanel());
        f.pack();
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                create();
            }
        });
    }
}


If you can run this from your IDE or attach remotely with the debugger it would be pretty easy to just set a breakpoint on the methods that set the size.

Or alternately, you could subclass JFrame with your own class and similarly override those methods and do

try { throw new Exception("here!"); } catch(Exception e) { e.printStackTrace(); }

That would tell you what is causing the change in size.


Sounds like the layout manager kicking in. Try running with the Swing Explorer to see what it thinks of the world.

0

精彩评论

暂无评论...
验证码 换一张
取 消