Re: Place JComponent in center of JDialog



Martijn Mulder wrote:
I have a JComponent that displays an image. I set the getPreferredSize() method
to the dimensions of the image, so when I add it to the content pane of a
JDialog, it fits exactly. When I resize the JDialog, I want the image to be
displayed in the exact center of the content pane. Setting the LayoutManager to
FlowLayout.CENTER doesn't work, the position is not vertically adjusted.
BorderLayout("Center") leaves the image in the top left corner. Howto?


You need a LayoutManager that doesn't adjust the size of your component up to fit the container. GridBagLayout will do that just fine.


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class test2 {
    public static void main(String[] args) {
        Runnable r = new Runnable() {
            public void run() {
                JFrame f = new JFrame();
                f.setLayout(new GridBagLayout());
                GridBagConstraints c = new GridBagConstraints();
                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                JPanel p = new JPanel();
                p.setPreferredSize(new Dimension(400,300));
                p.setBackground(Color.BLUE);
                f.add(p,c);
                f.pack();
                f.setVisible(true);
            }
        };
        EventQueue.invokeLater(r);
    }
}

--

Knute Johnson
email s/nospam/knute/
.