0

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?

Patrick
  • 17,669
  • 6
  • 70
  • 85
Nikki
  • 3,664
  • 2
  • 15
  • 14
  • 6
    *"please just humor me on this"* No. ***Use layouts!*** By the time you can figure the logic of laying out components in a custom way, that logic is worth putting into a custom layout. But first learn how to use the **existing** layouts. – Andrew Thompson Sep 22 '12 at 07:23
  • @AndrewThompson but I wanna know wwhhhyyyyyyyyyyyyy! I promise I'll go learn more about layoutmanagers if you just tell me why. :( – Nikki Sep 22 '12 at 07:39
  • I promise I won't *need* to tell you why if you learn about layout managers. – Andrew Thompson Sep 22 '12 at 07:40
  • 1
    @AndrewThompson ok sensei. If that's how it's gonna be, but bookmark this thread cause when I eventually figure it out, I'll be back someday to answer my own question. That's a promise! – Nikki Sep 22 '12 at 07:49

1 Answers1

2

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.

kleopatra
  • 51,061
  • 28
  • 99
  • 211