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();
}
});
}
}

