当前位置: 首页 > 知识库问答 >
问题:

在fxml、java fx中,根据对子UI的单击更新父UI

梁丘凯定
2023-03-14
package smartsql.connection.sqleditor;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Tab;
import javafx.scene.control.TextField;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.Callback;
import org.springframework.jdbc.core.JdbcTemplate;
import static smartsql.SmartSQL.appContext;
import smartsql.connection.ConnectionDO;
import smartsql.leftpane.CreateDB.CreateDBController;

/**
 *
 * @author manoj
 */
public class SQLTab extends Tab {

    ObservableList<String> lstDatabase;
    public TreeView databaseView = new TreeView();

    public SQLTab(JdbcTemplate jdbcTemplate) {
        try {
            System.out.println("inside sqlTAb constructor");
            ObservableList<String> lstDatabase = SQLEditorDAO.getDatabaseDetails(jdbcTemplate);
            System.out.println("inside treeviewww");
            this.lstDatabase = lstDatabase;
            ConnectionDO  cdo = appContext.getBean(ConnectionDO.class);

            TreeItem<String> root = new TreeItem<String>(cdo.getUsername()+"@"+cdo.getHost());

            databaseView.getStylesheets().add(getClass().getResource("/smartsql/css/SQLTab.css").toExternalForm());
            for (String itemString : lstDatabase) {
                System.out.println("addingggg:::" + itemString);
                TreeItem<String> database = new TreeItem<String>(itemString);
                root.getChildren().add(database);
                ObservableList<String> lstTables = SQLEditorDAO.getTableDetails(jdbcTemplate, itemString);
                TreeItem<String> table = new TreeItem<String>("Tables");
                for (String tableName : lstTables) {
                    table.getChildren().add(new TreeItem<String>(tableName));
                }
                database.getChildren().add(table);

                //adding for stored procedures
                ObservableList<String> lstStoredProcedures = SQLEditorDAO.getStoredProcedureDetails(jdbcTemplate,itemString);
                TreeItem<String> storedProcedures = new TreeItem<String>("Stored Procedures");
                for (String procedureName : lstStoredProcedures) {
                    storedProcedures.getChildren().add(new TreeItem<String>(procedureName));
                }
                database.getChildren().add(storedProcedures);


                //adding for triggers
                ObservableList<String> lstTriggers = SQLEditorDAO.getTriggersDetails(jdbcTemplate,itemString);
                TreeItem<String> triggers = new TreeItem<String>("Triggers");
                for (String triggerName : lstStoredProcedures) {
                    storedProcedures.getChildren().add(new TreeItem<String>(triggerName));
                }
                database.getChildren().add(triggers);


                //adding for triggers
                ObservableList<String> lstEvents = SQLEditorDAO.getEventsDetails(jdbcTemplate,itemString);
                TreeItem<String> events = new TreeItem<String>("Events");
                for (String eventName : lstStoredProcedures) {
                    storedProcedures.getChildren().add(new TreeItem<String>(eventName));
                }
                database.getChildren().add(events);

            }
            databaseView.setRoot(root);

            databaseView.setCellFactory(new Callback<TreeView<String>,TreeCell<String>>(){
                @Override
                public TreeCell<String> call(TreeView<String> p) {
                    return new TextFieldTreeCellImpl();
                }
            });
            setContent(databaseView);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    private final class TextFieldTreeCellImpl extends TreeCell<String>{
        private ContextMenu addMenu = new ContextMenu();
        private TextField textField;
        public TextFieldTreeCellImpl() {

        }

        @Override
        public void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);

            // if the item is not empty and is a root...
            if (!empty && getTreeItem().getParent() == null) {
                MenuItem addMenuItem = new MenuItem("Create Database");
                // addMenu.getItems().add(addMenuItem);
                addMenuItem.setOnAction(new EventHandler() {
                    public void handle(Event t) {
                        System.out.print( "item text is : "+getText());
                        if(getText().contains("@")){
                            //TreeItem newEmployee =
//                        new TreeItem<String>("Create Database");
//                            getTreeItem().getChildren().add(newEmployee);

                            try {
                                FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/smartsql/leftpane/CreateDB/CreateDB.fxml"));
                                Parent node =fxmlLoader.load();
                                Stage stage = new Stage();
                                stage.initModality(Modality.APPLICATION_MODAL);
                                stage.setTitle("Create Database");
                                stage.setScene(new Scene(node));
                                stage.initStyle(StageStyle.UTILITY);
                                stage.resizableProperty().setValue(Boolean.FALSE);
                                stage.show();
                            } catch (IOException ex) {
                                Logger.getLogger(SQLTab.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }

                });
                //   CreateDBController a= appContext.getBean(CreateDBController.class);
//                Update u = appContext.getBean(Update.class);
//                if(u.name!=null)
//                         System.out.print("newly added name: "+u.name);
                        addMenu.getItems().clear();
                        new TreeItem<String>();
//                            getTreeItem().getChildren().add(newEmployee);
                        addMenu.getItems().add(addMenuItem);
                        setContextMenu(addMenu);
            }

            if (empty) {
                setText(null);
                setGraphic(null);
            } else {
                if (isEditing()) {
                    if (textField != null) {
                        textField.setText(getString());
                    }
                    setText(null);
                    setGraphic(textField);
                } else {
                    setText(getString());
                    setGraphic(getTreeItem().getGraphic());
                    if (
                            !getTreeItem().isLeaf()&&getTreeItem().getParent()!= null
                            ){
                        MenuItem addMenuItem = new MenuItem("Create Database1");
                        addMenu.getItems().add(addMenuItem);
                        addMenuItem.setOnAction(new EventHandler() {
                            public void handle(Event t) {
                                System.out.print( "item text is : "+getText());
                                if(getText().contains("@")){
                                    TreeItem newEmployee =
                                            new TreeItem<String>("Create Database");
                                    getTreeItem().getChildren().add(newEmployee);

                                    try {
                                        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/smartsql/leftpane/CreateDB/CreateDB.fxml"));
                                        Parent node =fxmlLoader.load();

                                        Stage stage = new Stage();
                                        stage.initModality(Modality.APPLICATION_MODAL);
                                        stage.setTitle("Create Database");
                                        stage.setScene(new Scene(node));
                                        stage.initStyle(StageStyle.UTILITY);
                                        stage.resizableProperty().setValue(Boolean.FALSE);
                                        stage.show();
                                    } catch (IOException ex) {
                                        Logger.getLogger(SQLTab.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                }
                            }

                        });
                        addMenu.getItems().clear();
                        addMenu.getItems().add(addMenuItem);
                        setContextMenu(addMenu);
                    }
                    if (
                            getTreeItem().isLeaf()&&getTreeItem().getParent()!= null
                            ){
                        MenuItem addMenuItem = new MenuItem("Create Database2");
                        addMenu.getItems().add(addMenuItem);
                        addMenuItem.setOnAction(new EventHandler() {
                            public void handle(Event t) {
                                System.out.print( "item text is : "+getText());
                                if(getText().contains("@")){
                                    TreeItem newEmployee =
                                            new TreeItem<String>("Create Database");
                                    getTreeItem().getChildren().add(newEmployee);
                                    try {
                                        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/smartsql/leftpane/CreateDB/CreateDB.fxml"));
                                        Parent node =fxmlLoader.load();

                                        Stage stage = new Stage();
                                        stage.initModality(Modality.APPLICATION_MODAL);
                                        stage.setTitle("Create Database");
                                        stage.setScene(new Scene(node));
                                        stage.initStyle(StageStyle.UTILITY);
                                        stage.resizableProperty().setValue(Boolean.FALSE);
                                        stage.show();
                                    } catch (IOException ex) {
                                        Logger.getLogger(SQLTab.class.getName()).log(Level.SEVERE, null, ex);
                                    }
                                }
                            }

                        });

                        addMenu.getItems().clear();
                        addMenu.getItems().add(addMenuItem);
                        setContextMenu(addMenu);
                    }
                }
            }
        }
        private String getString() {
            return getItem() == null ? "" : getItem().toString();
        }
        private void createTextField() {
            textField = new TextField(getString());
            textField.setOnKeyReleased(new EventHandler<KeyEvent>() {

                @Override
                public void handle(KeyEvent t) {
                    if (t.getCode() == KeyCode.ENTER) {
                        commitEdit(textField.getText());
                    } else if (t.getCode() == KeyCode.ESCAPE) {
                        cancelEdit();
                    }
                }
            });
        }
    }


}
<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import java.net.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="200.0" prefWidth="300.0" xmlns="http://javafx.com/javafx/8"  xmlns:fx="http://javafx.com/fxml/1" fx:controller="smartsql.leftpane.CreateDB.CreateDBController">
    <stylesheets>
        <URL value="@createdb.css"/>
    </stylesheets>
    <children>
        <GridPane layoutX="14.0" layoutY="15.0" prefHeight="20.0" prefWidth="500.0"  >
            <columnConstraints>
                <ColumnConstraints hgrow="SOMETIMES" maxWidth="120.0" minWidth="100.0" prefWidth="175.0" />
                <ColumnConstraints hgrow="SOMETIMES" maxWidth="128.0" minWidth="100.0" prefWidth="175.0" />
            </columnConstraints>
            <rowConstraints>
                <RowConstraints minHeight="10.0" prefHeight="10.0" vgrow="SOMETIMES" />
                <RowConstraints minHeight="10.0" prefHeight="10.0" vgrow="SOMETIMES" />
                <RowConstraints minHeight="10.0" prefHeight="10.0" vgrow="SOMETIMES" />
            </rowConstraints>
            <children>
                <Label text="Database Name" GridPane.rowIndex="1"  >
                </Label>

                <Label text="Database Charset" GridPane.rowIndex="2"/>
                <Label text="Database Collation" GridPane.rowIndex="3"/>
                <TextField fx:id="txtDatabaseName" promptText="Database Name" GridPane.columnIndex="1">
                </TextField>
                <ChoiceBox fx:id="txtCharset" prefWidth="500.0" GridPane.columnIndex="1" GridPane.rowIndex="2">
                </ChoiceBox> 
                <ChoiceBox fx:id="txtCollation" prefWidth="500.0" GridPane.columnIndex="1" GridPane.rowIndex="3">
                </ChoiceBox>
                <Button fx:id="createDatabase" minWidth="-Infinity" mnemonicParsing="false" onAction="#handleNewDatabase" text="Create" prefWidth="70.0" GridPane.rowIndex="4" GridPane.columnIndex="1"   />
                <Button fx:id="cancel" minWidth="-Infinity" mnemonicParsing="false" onAction="#handleCancel" prefWidth="70.0" text="Cancel" GridPane.columnIndex="2" GridPane.rowIndex="4"  />

            </children>
        </GridPane>
    </children>
</AnchorPane>

createdbcontroller.java

package smartsql.leftpane.CreateDB;

import java.lang.reflect.Method;
import java.net.URL;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.springframework.jdbc.core.JdbcTemplate;
import static smartsql.SmartSQL.appContext;
import smartsql.connection.ConnectionDO;
import smartsql.connection.MySQLConnectionController;
import smartsql.connection.MySQLConnectionManager;
import smartsql.connection.sqleditor.SQLEditor;
import smartsql.connection.sqleditor.SQLEditorDAO;
import smartsql.connection.sqleditor.SQLTab;
import smartsql.connection.sqleditor.Update;

public class CreateDBController extends MySQLConnectionController implements Initializable {

    /**
     * Initializes the controller class.
     */

    @FXML
            ChoiceBox txtCharset;
    @FXML
            ChoiceBox txtCollation;
    @FXML
            TextField txtDatabaseName;
    @FXML

            Button createDatabase;
    @FXML

            Button cancel;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        ConnectionDO  cdo = appContext.getBean(ConnectionDO.class);
        Update update = appContext.getBean(Update.class);
        update.bindName(txtDatabaseName.textProperty());

        MySQLConnectionManager connManager = appContext.getBean(MySQLConnectionManager.class);
        JdbcTemplate jdbcTemplate;
        try {
            jdbcTemplate = connManager.connect(cdo);
            ObservableList<String> charset = CreateDBDAO.getCharset(jdbcTemplate);
            txtCharset.setItems((ObservableList) charset);
            txtCharset.getItems().add("[default]");
            txtCharset.getSelectionModel().selectLast();

            ObservableList<String> collation = CreateDBDAO.getCollation(jdbcTemplate);
            txtCollation.setItems(collation);
            txtCollation.getItems().add("[default]");
            txtCollation.getSelectionModel().selectLast();


        } catch (Exception ex) {
            Logger.getLogger(CreateDBController.class.getName()).log(Level.SEVERE, null, ex);
        }


    }
    @FXML
    private void handleNewDatabase(ActionEvent even) {
        Stage stage = (Stage)createDatabase.getScene().getWindow();
        ConnectionDO  cdo = appContext.getBean(ConnectionDO.class);
        MySQLConnectionManager connManager = appContext.getBean(MySQLConnectionManager.class);
        JdbcTemplate jdbcTemplate;
        try {
            jdbcTemplate = connManager.connect(cdo);
            String dbName=txtDatabaseName.getText();
            CreateDBDAO.createDatabase(dbName,jdbcTemplate);

            stage.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    @FXML
    private void handleCancel() {
        Stage stage = (Stage)cancel.getScene().getWindow();
        stage.close();
    }
//    public String getDatabaseName(){
//        if(txtDatabaseName.getText()!=null)
//            return txtDatabaseName.getText();
//        else return  " s";
//    }
}

我想更新那个树景。

共有1个答案

施学
2023-03-14

当您显示包含createdb.fxml的对话框时(我在您的代码中看到了三次),而不是

stage.show();

stage.showAndWait() ;
CreateDBController controller = fxmlLoader.getController();
Optional<String> db = controller.getDatabaseName();
db.ifPresent(dbName -> {
    // do whatever you need with dbName, e.g.
    databaseView.getRoot().getChildren().add(new TreeItem<>(dbName));
});

这将阻止执行,直到对话框被取消(即用户按OK或取消)。然后获取对控制器的引用并从中检索数据。使用可选的可以方便地处理用户取消时的“no value”。

public class CreateDBController ... {

    private Optional<String> databaseName ;

    // ... other code as before

    @FXML
    private void handleNewDatabase(ActionEvent even) {
        Stage stage = (Stage)createDatabase.getScene().getWindow();
        ConnectionDO  cdo = appContext.getBean(ConnectionDO.class);
        MySQLConnectionManager connManager = appContext.getBean(MySQLConnectionManager.class);
        JdbcTemplate jdbcTemplate;
        try {
            jdbcTemplate = connManager.connect(cdo);
            String dbName=txtDatabaseName.getText();
            CreateDBDAO.createDatabase(dbName,jdbcTemplate);

            databaseName = Optional.of(dbName);

            stage.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    @FXML
    private void handleCancel() {
        Stage stage = (Stage)cancel.getScene().getWindow();
        databaseName = Optional.empty();
        stage.close();
    }

    public Optional<String> getDatabaseName() {
        return databaseName ;
    }
}    
 类似资料:
  • null 我是否可以从子控制器-b更改父FXML-A中标签的文本?

  • 我正在创建一个简单的天气应用程序 以下是我问题的细节:- 我浏览了javafx@docs.oracle.com的完整文档。没运气。在这里我也没有得到答案。请引导。

  • 我正在使用JavaFX开发一款扫雷游戏: 我的是由组成的,我试图找到一种方法来计算在上单击的图像的列和行索引。我目前有这个代码: 但是,方法和返回。我做错了什么?

  • 我需要你的帮助来解决这个问题,我想从不同的包中包含子fxml。如果child.fxml在同一位置,我可以将它们包含到parent.fxml中,但不知道如何将child.fxml添加到parent.fxml中,当两者都在不同的位置/包中时。 先谢谢你。

  • 我有一个表视图 以下是我的表格创建: 我的自定义细胞工厂代码:

  • 几天来,我一直在尝试更新Javafx用户界面,同时自动发送2封或更多的电子邮件。UI应该用“连接”、“发送”和“已发送”来更新标签。我读过关于Runnables,Tasks,TimeLine的文章,但是我真的不知道我应该使用哪种方法,以及它是如何工作的。 在我阅读Platform.runLater()的任何地方,我都使用它,但是我的JavaFX Gui中的动画冻结了,只有当所有的电子邮件都已发送时