Siirry pääsisältöön

Navigate to another view programmatically

Call Router.getCurrent().navigate() from anywhere in your Java code, such as from a button click handler. Passing the view class is preferred over a raw URL string so the router handles URL generation automatically.

import com.webforj.component.Composite;
import com.webforj.component.button.Button;
import com.webforj.component.html.elements.Div;
import com.webforj.router.Router;
import com.webforj.router.annotation.Route;

@Route
public class HomeView extends Composite<Div> {
private final Div self = getBoundComponent();
private final Button goToDashboard = new Button("Go to Dashboard");

public HomeView() {
goToDashboard.onClick(e -> Router.getCurrent().navigate(DashboardView.class));
self.add(goToDashboard);
}

@Route("dashboard")
public static class DashboardView extends Composite<Div> {}
}

To navigate with route parameters, pass a ParametersBag as the second argument: Router.getCurrent().navigate(UserView.class, ParametersBag.of("id=42")).