views:

2000

answers:

4

Bit of oddness, seen if I do the following:

import javax.swing.*;
public class FunkyButtonLayout {
    public static void main(String[] args) {
        JFrame frame = new JFrame("");
        JPanel j0 = new JPanel();     // j0 gets added to the root pane
        j0.setLayout(null);
        JPanel j1 = new JPanel();     // j1 gets added to j0 
        j1.setLayout(null);
        JButton b1 = new JButton(""); // b1 gets added to j1
        j1.add(b1);
        b1.setBounds(0, 0, 40, 32);   // b1 is big
        j0.add(j1);
        j1.setBounds(0, 0, 32, 32);   // j1 is not so big - b1 gets 'trimmed'
        frame.getContentPane().setLayout(null); // <- seems to be needed :-(
        frame.getContentPane().add(j0);             
        j0.setBounds(10, 10, 32, 32); // end result: a 32x32 button with
        frame.setSize(125, 125);      // a trimmed right border
        frame.setVisible(true);       // in the top-left corner
    }
}

I get pretty much what I'm looking for, apart from the ability to position j0 in the root pane with a layout manager. If I change the

        frame.getContentPane().setLayout(null);

line to

        frame.getContentPane().setLayout(new java.awt.FlowLayout());

I see j0 draw as a 1x1 pixel @ the middle of the screen :-(

Any ideas why? Note that this isn't just a FlowLayout thing - pretty much every layout manager messes this up.

I really want to have the net effect of the 'border trimmed on one side' button - it allows me to do the toolbar-button-cluster thing (the kind of thing that cage fighter tries to get rid of) with native-looking button controls - I cannot see another way of doing this, thanks to OS-level skins. So any ideas appreciated :-)

+4  A: 

If you set the layout manager to null, you have to explicitly set the container's preferred size (that's why it's showing up so small).

If you are using setBounds on a component, you are over-riding the work that the layout manager for the parent container does.

I would remove all calls to setBounds and all calls to setLayout(null) and try to achieve the effect you are after using just layout managers.

Dan Dyer
You da man! Well, almost ;-) "using the layout managers the way they were intended to be used" doesn't buy me the hack I'm looking for.However adding j0.setPreferredSize(new java.awt.Dimension(32, 32)); after the j0.setBounds line resolves the issue. Thanks!!!!!
Dave Carpeneto
+1  A: 
OscarRyz
</quote> Perhaps I should've stopped there </quote> Reely, reely glad you didn't - I learned quite a lot from the code you presented - thanks :-)
Dave Carpeneto
+1  A: 

For a really good explanation of how layout managers work, check out an old article I wrote at Sun

http://developer.java.sun.com/developer/onlineTraining/GUI/AWTLayoutMgr/

It's old, but talks about preferredSize and layout nesting pretty well.

Enjoy, -- Scott

Scott Stanchfield
A: 
Dave Carpeneto