У меня есть проект из uni, где мне нужно создать приложение с Java (в формате контроллера представления модели), и я хочу сделать вкладки в своем приложении, но, похоже, он не работает.
Я просмотрел множество руководств, и все они рассказывают мне один и тот же способ использования TabPane, но у меня это не работает.
Вот код, который у меня есть в моем классе загрузчика приложений:
package main;
import controller.ModuleChooserController;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.stage.Stage;
import model.StudentProfile;
import view.ModuleChooserRootPane;
public class ApplicationLoader extends Application {
private ModuleChooserRootPane view;
@Override
public void init() {
//create model and view and pass their references to the controller
StudentProfile model = new StudentProfile();
view = new ModuleChooserRootPane();
new ModuleChooserController(view, model);
}
@Override
public void start(Stage stage) throws Exception {
//whilst you can set a min width and height (example shown below) for the stage window,
//you should not set a max width or height and the application should
//be able to be maximised to fill the screen and ideally behave sensibly when resized
stage.setMinWidth(530);
stage.setMinHeight(500);
TabPane tabPane = new TabPane();
Tab tab = new Tab("Testing");
tabPane.getTabs().add(tab);
stage.setTitle("Final Year Module Chooser Tool");
stage.setScene(new Scene(view));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
У меня реализована TabPane, но ничего не появляется. Я также пробовал реализовать TabPane в моем пакете "view", но и там мне не повезло.
Вот код для ModuleRootChooserPane:
package view;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
//You may change this class to extend another type if you wish
public class ModuleChooserRootPane extends BorderPane {
private ButtonPane bp;
private ProfileCreator profileCreator;
public ModuleChooserRootPane() {
//This sets the colour of background
this.setStyle("-fx-background-color: #EDF1F3;");
//Creates a new instance of the buttonPane (Used from ButtonPane.java) and ProfileCreator
bp = new ButtonPane();
profileCreator = new ProfileCreator();
//This adds the padding on the left so that "submit" button is in line with text fields
bp.setPadding(new Insets(0, 0, 0, 120));
//Creates a new VBox which adds the ProfileCreator and the button pane
VBox rootContainer = new VBox(profileCreator, bp);
rootContainer.setPadding(new Insets(100,100,100,100));
this.getChildren().add(rootContainer);
}
}
@azro я поставил :)




Вы выбираете работу без файла fxml, поэтому вам нужно создать свое представление в классе ModuleChooserRootPane, каждый графический элемент должен быть здесь, или в других классах, используемых здесь.
Так что вам также нужно добавить свой TabPane в его конструктор:
public ModuleChooserRootPane() {
...
//this.getChildren().add(rootContainer);
setLeft(rootContainer); // or Top/Bottom/Right/Center
TabPane tabPane = new TabPane();
Tab tab = new Tab("Testing");
tabPane.getTabs().add(tab);
setCenter(tabPane); // or Top/Bottom/Right/Left
}
BorderPane - хорошая идея для корневого элемента, потому что у него есть несколько зон для добавления элемента, но для этого вам нужно использовать setLeft(), setRight(), setCenter(), setTop() and setBottom(), а не просто getChildren().add(), где вы не можете контролировать место
Пример добавления содержимого на разные вкладки:
TabPane tabPane = new TabPane();
Tab tab = new Tab("Testing");
tab.setContent(new VBox(new Label("Here is the testing place"), new Circle(15, 12, 10)));
Tab tab2 = new Tab("Testing2");
HBox hboxContentTab2 = new HBox();
hboxContentTab2.getChildren().add(new Ellipse(10, 10, 10, 13));
hboxContentTab2.getChildren().add(new Label("Here is the BIS testing place"));
tab2.setContent(hboxContentTab2); // add a Node created before, ot can be whatever you wan, borderpane, gridpane, hbox, vbox, label ...
tabPane.getTabs().addAll(tab, tab2);
Это сработало!!! Большое спасибо, чувак! Я добавил "setTop (tabPane);" и это сработало. Я очень ценю это: D
@ImperfectLion хорошо;) не забывайте всегда использовать setCenter/Top/Bottom/Left/Right при работе с BorderPane. Вы имеете в виду добавление содержимого во вкладки? Я, например, редактировал, ищу
Спасибо, можно ли использовать tab2.setContent () в нескольких строках или это должно быть в одной строке?
@ImperfectLion можно несколько, ищите вкладку 2
Боже мой, я только что починил. Честно говоря, мужик, спасибо за вашу помощь, я очень ценю это: D
Вы создали TabPane, но никогда не добавляли ее где-нибудь ^^