Link to home
Start Free TrialLog in
Avatar of allelopath
allelopath

asked on

SpringLayout problem

Why doesn't the button appear?

package springlayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SpringLayout;

public class SpringLayoutTest extends JPanel{

	public SpringLayoutTest() {
		
		SpringLayout mySpringLayout = new SpringLayout();
		JPanel myPanel = new JPanel(mySpringLayout);

		JButton helloButton = new JButton("hello");
		myPanel.add(helloButton);

		mySpringLayout.putConstraint(SpringLayout.WEST, helloButton, 10, SpringLayout.WEST, myPanel);
		mySpringLayout.putConstraint(SpringLayout.NORTH, helloButton, 10, SpringLayout.NORTH, myPanel);

		this.add(myPanel);
	}

	/**
	 * 
	 * @param s
	 */
	public static void main(String s[]) {

		JFrame frame = new JFrame("SpringLayoutTest");

		SpringLayoutTest springLayoutTest = new SpringLayoutTest();

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setContentPane(springLayoutTest);
		frame.setSize(300, 300);
		frame.setLocation(300,300);
		frame.setVisible(true);
	}
	
}

Open in new window

Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

You didn't set the layout on the Container. Try the following
    public SpringLayoutTest() {
        SpringLayout mySpringLayout = new SpringLayout();
	setLayout(mySpringLayout);

        JButton helloButton = new JButton("hello");
        add(helloButton);

        mySpringLayout.putConstraint(SpringLayout.WEST, helloButton, 10,
            SpringLayout.WEST, this);
        mySpringLayout.putConstraint(SpringLayout.NORTH, helloButton, 10,
            SpringLayout.NORTH, this);

    }

Open in new window

Avatar of allelopath
allelopath

ASKER

That's not what I'm looking to do. I want a JPanel that contains a JPanel that is using SpringLayout.

OK. Just use your code, but do
myPanel.setLayout(mySpringLayout);

Open in new window

Does this accomplish that?
JPanel myPanel = new JPanel(mySpringLayout);

Open in new window

Yes, that'll do it
I already have that, in the original code
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That works, but I don't understand why. JPanel has FlowLayout as a default layout manager. Why do I have to explicitly set a layout manager?
It's a question of how the subpanel behaves as far as sizing is concerned
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial