Layout.setDefaultComponentAlignment() doesn't work

I’m trying to write a simple login form component, in lieu of LoginForm which is being deprecated. The main difference is that I want to put my widgets horizontally rather than vertically, so that component may be on top of the page.

The problem is, using setDefaultComponentAlignment(Alignment.TOP_RIGHT) is simply ignored by widgets. They are aligned top left no matter what.

Here’s my code:

import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;

public class LoginComponent extends CustomComponent {

	public LoginComponent() {
		HorizontalLayout layout = new HorizontalLayout();
		layout.setDefaultComponentAlignment(Alignment.TOP_RIGHT);
		layout.addComponent(new Label("Login:"));
		layout.addComponent(new TextField());;
		layout.addComponent(new Label("Password:"));
		layout.addComponent(new PasswordField());
		layout.addComponent(new Button());
		
		System.out.println(layout.getDefaultComponentAlignment().toString());
		System.out.println(Alignment.TOP_RIGHT.toString());
			
		setCompositionRoot(layout);
	}

}

System.out.println() calls are my rudimentary attempts at debugging the issue, and it shows that indeed Alignment.TOP_RIGHT is set, but widgets in layout don’t conform.

Is the Layout and the CustomComponent on 100% or another respectable big size? Check if all the Components you added to the layout have an undefined width and that they don’t try to expand over the entire space.

At least Labels are 100% wide by default, so they might just
seem
to be aligned to the left (unless you have an RTL language, I suppose). setSizeUndefined() should help.

I’ve tried on Labels, but they were still aligned left, so I thought it may be also the case with other components and added:


import java.util.Iterator;
import com.vaadin.ui.Component;
...
Iterator<Component> iterator = layout.iterator();
while ( iterator.hasNext() ) {
	iterator.next().setSizeUndefined();
}

To no effect, widgets are still aligned top left.

Is your CustomComponent / the layout wider then the components inside? Check that with a Dev Tool like Firebug.

Btw. I don’t think that layout.iterator works although i’m not sure. I would’ve looked for something like layout.GetComponents() if that exists or something similar.

The interface HasComponents extends Iterable and has a method iterator(), so that part should work.

As Marius said, I think the most likely problem is that your layout shrinks to the size of its contents - as a general rule (with exceptions possible when you understand how it works) the contained components should have undefined size but the layout itself should have a defined size - either full size or an explicit pixel size or such. Also all the parents of the layout need to have a defined size.