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/
Martijn:
You are very welcome. If I had realized you were using 1.4 I would have
written it differently.
//How to place a component in the center of its parent
//Original code by Knute Johnson
//Adapted for the millions by Martijn Mulder
//One class test3 is all it takes
public class test3
{
//One method main is all it takes
public static void main(String[] args)
{
//create JPanel, paint it blue, set preferred size
> You can use BorderLayout.Center
Sure, but that does not provide the effect Martijn was after.
A BorderLayout.CENTER will put the component in the center
and *stretch* it to fit the available space, as opposed to
putting it in the center and *padding* the outside..
See Knute's solution for exactly what the OP wanted.
--
Andrew Thompson
http://www.PhySci.org/codes/ Web & IT Help
http://www.PhySci.org/ Open-source software suite
http://www.1point1C.org/ Science & Technology
http://www.LensEscapes.com/ Images that escape the mundane
> You are very welcome. If I had realized you were using 1.4 I would have
> written it differently.
Is running your app in a hand-made thread a recommendation in Java 5?
Funky! I tried 5 but java.exe takes forever to start so I switched back to
1.3.1 for faster development circles. I'm stuck with books that cover
java 1.1 and some less-than-perfect java2 references so I'm not really
up-to-date. But code examples have always been my way of learning.
To be thread safe for Swing. See this article:
http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html