Nikki
Nikki

Reputation: 3674

Adding/changing JLabels affecting parent's setBounds

I'm still new to Java and I'm enjoying messing around with it, so please just humor me on this. I know about the layout manager but I'm interested in the mechanics of swing so I'm using absolute positioning. Any insights would be greatly appreciated.

So I've noticed an annoying behavior when I add a JLabel to a JPanel. For Example if I set it up like this:

JFrame frame=new JFrame("Test Frame");
frame.setSize(800,500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable (false);
JPanel conPane=new JPanel();
conPane.setLayout(null);
frame.setContentPane(conPane);
conPane.setBounds(0,0,1600,1000);
conTP.setFocusable(true);
frame.setVisible(true);

So now I move the conPane panel...

conPane.setBounds(-200,-200,1600,1000);

And then make a new JLabel....

ImageIcon ico=new ImageIcon("directory/testimage.gif");
JLabel myLabel=new JLabel(ico);myLabel.setLayout(null);
myLabel.setBounds(300,300,200,200);

And add it to conPane...

conPane.add(myLabel);

And it resets conPane back to it's starting position. Essentially doing setBounds(0,0,1600,1000) without my permission;

It also happens if I move a label, change it's icon or pretty much do anything involving altering a child of conPane.

How can I stop it?

Upvotes: 0

Views: 310

Answers (1)

kleopatra
kleopatra

Reputation: 51524

And it resets conPane back to it's starting position

Essentially, that's wrong. It's wrong because your assumption is wrong: you assume that

contPane.setBounds(....)

has an effect when actually it doesn't: the layoutManager that's responsible for laying out a component is the manager of its parent (which in this context is RootPaneLayout which you definitely don't want to mess up). That manager sets it to the size of the frame (- insets - menubar), no matter what you do. You can visualize that by setting a border to the contentPane:

contPane.setBorder(BorderFactory.createLineBorder(Color.RED, 5)); 

At the end of the day, there is absolutely no way around learing all about layouts, even if you insist on wasting time by not using it.

Upvotes: 2

Related Questions