positioning JPanels?

The following code creates a JFrame that is 300x200 pixels with a red background. Then it adds a pink 30x30 JPanel to the center of the frame. Then I tried to cover up the pink JPanel by adding a black 30x30 JPanel to the center of the frame.When I executed the code, I expected to see a 30x30 black panel in the middle of the JFrame's red background. However, I get a 30x30 pink square in the upper left corner of the window at (0,0), and the rest of the JFrame was black. Can someone explain that?

I did a couple more experiments, like commenting out the code that adds the black JPanel, and then the whole JFrame was pink. Why did java ignore my setSize() command on the pink JPanel?

What I really want to do is absolutely position two colored squares in a JFrame and move them to new coordinates in response to a user's mouse actions.

import javax.swing.*;

publicclass AATest1

{

publicstaticvoid createAndShowGui()

{

JFrame window =new JFrame("title");//Defaul BorderLayout

window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

window.setBounds(10, 10, 300, 200);

Container cpane = window.getContentPane();

cpane.setBackground(Color.red);

//add pink JPanel:

JPanel panel =new JPanel();

panel.setBackground(Color.pink);

panel.setSize(30, 30);

cpane.add(panel, BorderLayout.CENTER);

//add black JPanel on top of pink JPanel:

JPanel panelB =new JPanel();

panelB.setBackground(Color.black);

panelB.setSize(30, 30);

cpane.add(panelB, BorderLayout.CENTER);

window.setVisible(true);

}

publicstaticvoid main(String[] args)

{

SwingUtilities.invokeLater(new Runnable()

{

publicvoid run()

{

createAndShowGui();

}

});

}

}

[2749 byte] By [7studa] at [2007-10-3 9:28:03]
# 1
If you want to use absolute positioning, you need to add:cpane.setLayout(null);
CaptainMorgan08a at 2007-7-15 4:42:24 > top of Java-index,Java Essentials,New To Java...
# 2
You can't add 2 components to the same location on a BorderLayout (i.e. 2 panels in the CENTER). Layout Managers are designed to not overlap components, so you need to use an absolute layout if you want to manually overlap them.
hunter9000a at 2007-7-15 4:42:24 > top of Java-index,Java Essentials,New To Java...
# 3
Also, if you are using absolute positioning, you need to set the location as well as the size.
CaptainMorgan08a at 2007-7-15 4:42:24 > top of Java-index,Java Essentials,New To Java...
# 4
> Why did java ignore my setSize() command on the pink JPanel?LayoutManagers work withsetPreferredSize()A JFrame (itself) is not controlled by a LayoutManger, so it uses setSize()
Michael_Dunna at 2007-7-15 4:42:24 > top of Java-index,Java Essentials,New To Java...