UPDATE Parent的UI取决于点击fxml,java fx中的子UI

时间:2015-06-06 17:41:42

标签: java javafx javafx-8

我正在使用javafx创建像sqlyog这样的应用程序。我的问题是我想添加数据库。每当它添加时,它应该更新具有所有其他数据库的treeView。创建db的对话框出现,在给出名称和设置其他变量之后,它让用户添加数据库。如何掌握这个treeView?任何建议都将不胜感激。

SQLTab.java //具有树视图的类,其中包含数据库名称的树状项及其在树中的详细信息,即表名,触发器,存储过程等。

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();
                    }
                }
            });
        }
    }


}

获取数据库名称

的CreateDB.fxml
<?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";
//    }
}

我想更新那个treeView。

1 个答案:

答案 0 :(得分:0)

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

stage.show();

DO

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或取消)。然后,您将获得对控制器的引用并从中检索数据。在用户取消的情况下,使用Optional可以方便地处理“无价值”。

然后在CreateDBController中定义databaseName字段。在handleNewDatabase方法中将其设置为用户的值,并在handleCancel方法中将其设置为空:

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 ;
    }
}