use of javafx.scene.control.TreeItem in project DistributedFractalNetwork by Budder21.
the class FractalEditor method moveDown.
/**
* @param item
*/
private static void moveDown(TreeItem item) {
// TODO move layers down
System.out.println("moveDown");
if (item.nextSibling() != null && item.nextSibling().getValue() != null) {
TreeItem parent = item.getParent();
List<TreeItem> list = new ArrayList<TreeItem>();
boolean skip = false;
for (Object child : parent.getChildren()) {
if (child == item) {
list.add(((TreeItem) child).nextSibling());
list.add((TreeItem) child);
skip = true;
} else {
if (!skip)
list.add((TreeItem) child);
skip = false;
}
}
parent.getChildren().clear();
parent.getChildren().addAll(list);
}
}
use of javafx.scene.control.TreeItem in project DistributedFractalNetwork by Budder21.
the class FractalEditor method initialize.
/**
* Initializes the menus and fractal. Adds the various action listeners to all the GUI components. Constructs most of the
* GUI logic
*
* @author David
*
* @throws FileNotFoundException
* @throws AWTException
*/
@SuppressWarnings({ "rawtypes", "unchecked", "static-access" })
public void initialize() throws FileNotFoundException, AWTException {
// initializing stuff
Layer.initializeFractalRegistry();
File fractalDirectory = new File(Constants.FRACTAL_FILEPATH);
if (!fractalDirectory.exists()) {
fractalDirectory.mkdirs();
try {
fractalDirectory.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
}
fractal = new RenderManager();
selectedLayer = fractal.getLayers().get(0);
MenuBar menu = new MenuBar();
SwingNode fractalEditor = new SwingNode();
parameters = new TreeView();
layers = new TreeView();
VBox trees = new VBox();
trees.minHeightProperty().bind(bp.minHeightProperty().subtract(menu.minHeightProperty()));
trees.minWidthProperty().bind(bp.minWidthProperty().divide(6));
trees.setAlignment(Pos.CENTER);
Button render = new Button("Update");
render.setFont(new Font("Ariel", 36));
// TODO: change color of update button
render.minWidthProperty().bind(trees.minWidthProperty());
fractalView = new ImageView();
fractalView.setOnMouseClicked(e -> {
Point p = new Point(e.getScreenX(), e.getScreenY() - 52);
double screenDistX = fractalView.getFitWidth() / 2 - p.x;
double screenDistY = fractalView.getFitHeight() / 2 - p.y;
double realDistX = -screenDistX * fractal.getRealResolution().x / fractal.getScreenResolution().width;
double realDistY = screenDistY * fractal.getRealResolution().y / fractal.getScreenResolution().height;
fractal.setLocation(new Point(fractal.getLocation().x + realDistX * 2, fractal.getLocation().y + realDistY * 2));
this.updateFractalImage();
});
fractalView.setOnMouseEntered(e -> {
zoom = true;
});
fractalView.setOnMouseExited(e -> {
zoom = false;
});
this.setOnKeyPressed(e -> {
if (zoom)
if (e.getCode() == KeyCode.COMMA) {
this.fractal.setZoom(this.fractal.getZoom() * 1.5);
updateFractalImage();
} else if (e.getCode() == KeyCode.PERIOD) {
this.fractal.setZoom(this.fractal.getZoom() / 1.5);
updateFractalImage();
}
});
fractalView.setOnScroll(e -> {
double zoom = e.getDeltaY() > 0 ? 1 / .9 : .9;
this.fractal.setZoom(this.fractal.getZoom() * zoom);
this.updateFractalImage();
});
this.fractal = new RenderManager();
render.setOnAction(e -> {
updateFractalImage();
});
// Fitting the image to the screen
fractalView.fitWidthProperty().bind(bp.minWidthProperty().subtract(trees.minWidthProperty()));
fractalView.fitHeightProperty().bind(bp.heightProperty().subtract(menu.minHeightProperty()).subtract(220));
{
// Fitting gradientEditor to full screen
Dimension p = new Dimension((int) (Toolkit.getDefaultToolkit().getScreenSize().width * 0.75), 200);
System.out.println("Gradient Dimensions: " + p);
gradient = new Window(p, 50, this.fractal.getLayers().get(0));
}
{
// Tree Stuff
parameters.setRoot(new TreeItem());
parameters.getRoot().setExpanded(true);
parameters.setShowRoot(false);
parameters.setEditable(true);
// TODO if need click for params
/**
* parameters.setOnMouseClicked(new EventHandler<MouseEvent>(){
*
* @Override public void handle(MouseEvent event) { // TODO
* Auto-generated method stub
* if(event.getClickCount()==2){
* System.out.println("boop"); updateParams(); } }
*
* });
*/
parameters.setCellFactory(new Callback<TreeView, TreeCell<MetaParam>>() {
@Override
public TreeCell call(TreeView param) {
StringConverter s = new StringConverter() {
@Override
public String toString(Object object) {
return object.toString();
}
@Override
public Object fromString(String string) {
int index = string.indexOf(":");
if (!string.substring(index + 1, index + 2).equals(" "))
string = string.substring(0, index + 1) + " " + string.substring(index + 1);
Parameters params = new Parameters();
for (Object o : parameters.getRoot().getChildren()) {
TreeItem i = (TreeItem) o;
String msg = i.getValue().toString();
if (param.getSelectionModel().getSelectedItem().equals(o))
msg = string;
String key = msg.substring(0, msg.indexOf(":"));
String value = msg.substring(msg.indexOf(":") + 2);
params.put(key, value);
}
getSelectedLayer().setParameters(params);
updateFractalImage();
return new MetaParam(string.substring(0, string.indexOf(": ")), string.substring(string.indexOf(": ") + 2));
}
};
return new TextFieldTreeCell<MetaParam>(s) {
@Override
public void updateItem(MetaParam item, boolean empty) {
super.updateItem(item, empty);
}
};
}
});
layers.setRoot(new TreeItem());
layers.getRoot().setExpanded(true);
layers.setShowRoot(false);
// layers.setEditable(true);
// Use a custom callback to determine the style of the tree item
layers.setCellFactory(new Callback<TreeView, TreeCell>() {
@Override
public TreeCell call(TreeView param) {
return new CheckBoxTreeCell() {
@Override
public void updateItem(Object item, boolean empty) {
super.updateItem(item, empty);
// empty
if (empty) {
setGraphic(null);
setText(null);
// Otherwise if it's not representation as an
// item of the tree
// is not a CheckBoxTreeItem, remove the
// checkbox item
} else if (!(getTreeItem() instanceof CheckBoxTreeItem)) {
BufferedImage image;
try {
image = ImageIO.read(new File("textures\\plusButton.png"));
Image plusImage = SwingFXUtils.toFXImage(image, null);
ImageView plusView = new ImageView(plusImage);
plusView.setFitHeight(16);
plusView.setFitWidth(16);
setGraphic(plusView);
} catch (IOException e) {
e.printStackTrace();
}
}
setOnDragDetected(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
System.out.println("wofenh");
layers.getRoot().getChildren().remove(mouseEvent.getSource());
layers.layout();
}
});
}
};
}
});
TreeItem add = new TreeItem();
layerIndex = 1;
CheckBoxTreeItem item = getNewTreeItem();
layers.setOnMouseClicked(new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent mouseEvent) {
if (mouseEvent.getClickCount() == 1) {
if (layers.getSelectionModel().getSelectedItem() != add) {
updateParams();
}
if (layers.getSelectionModel().getSelectedItem() == add) {
CheckBoxTreeItem i = getNewTreeItem();
layers.getRoot().getChildren().add(0, i);
fractal.addLayer("HistogramLayer");
fractal.getLayers().get(fractal.getLayers().size() - 1).setName("Layer " + layerIndex);
updateFractalImage();
}
}
if (mouseEvent.getClickCount() == 2) {
if (layers.getSelectionModel().getSelectedItem() == add) {
} else {
((TreeItem) layers.getSelectionModel().getSelectedItem()).setValue(GradientMenus.displayLayerMenu((TreeItem<MetaLayer>) layers.getSelectionModel().getSelectedItem()));
MetaLayer meta = ((MetaLayer) ((TreeItem) layers.getSelectionModel().getSelectedItem()).getValue());
int index = layers.getRoot().getChildren().size() - 2 - layers.getRoot().getChildren().indexOf(layers.getSelectionModel().getSelectedItem());
Layer l = fractal.getLayers().get(index);
if (meta.isDelete()) {
fractal.getLayers().remove(index);
updateFractalImage();
layers.getRoot().getChildren().remove(layers.getSelectionModel().getSelectedItem());
layerIndex--;
return;
} else if (!meta.getType().equals(l.getClass().getSimpleName())) {
Layer newLayer = Layer.getLayerByType(meta.getType());
newLayer.init(l.getPalette(), index + 1);
l = newLayer;
fractal.getLayers().set(index, newLayer);
fractal.update();
updateParams();
}
l.setOpacity(meta.getOpacity());
fractal.getLayers().get(index).setName(meta.getName());
updateFractalImage();
}
} else if (mouseEvent.getClickCount() == 1 && layers.getSelectionModel().getSelectedItem() != add) {
int index = layers.getRoot().getChildren().size() - 2 - layers.getRoot().getChildren().indexOf(layers.getSelectionModel().getSelectedItem());
Layer l = fractal.getLayers().get(index);
gradient.updateLayer(l);
}
}
});
// TODO LAYER UP LAYER DOWN
layers.addEventFilter(KeyEvent.KEY_RELEASED, e -> {
if (e.getCode() == KeyCode.RIGHT) {
int index = this.fractal.getLayers().indexOf(getSelectedLayer());
moveUp((TreeItem) layers.getSelectionModel().getSelectedItem());
if (index < this.fractal.getNumLayers() - 1)
this.fractal.getLayers().add(index + 1, this.fractal.getLayers().remove(index));
}
if (e.getCode() == KeyCode.LEFT) {
moveDown((TreeItem) layers.getSelectionModel().getSelectedItem());
int index = this.fractal.getLayers().indexOf(getSelectedLayer());
if (index > 0)
this.fractal.getLayers().add(index - 1, this.fractal.getLayers().remove(index));
}
});
layers.getRoot().getChildren().addAll(item, add);
}
{
// This is the menu stuff
Menu network = new Menu("Network");
Menu fractal = new Menu("Fractal");
Menu system = new Menu("System");
MenuItem newNet = new MenuItem("Create New Network");
MenuItem viewNetLog = new MenuItem("View Network Log");
MenuItem viewNet = new MenuItem("View Network");
MenuItem endNet = new MenuItem("Close Network");
newNet.setOnAction(e -> {
NetworkCreationTool createNet = new NetworkCreationTool();
if (createNet.createNetwork()) {
this.network = createNet.getServer();
this.network.init(log);
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Network Message");
alert.setHeaderText(null);
alert.setContentText("Network succesfully created.");
viewNet.setDisable(false);
endNet.setDisable(false);
newNet.setDisable(true);
viewNetLog.setDisable(false);
alert.showAndWait();
}
});
viewNet.setDisable(true);
endNet.setDisable(true);
viewNetLog.setDisable(true);
viewNet.setOnAction(e -> {
Display display = new Display(this.network);
this.network.setDisplay(display);
display.updateNetworkView(this.network.getChildren(), this.network.getUncompletedJobs());
});
endNet.setOnAction(e -> {
// TODO: kill won't stop network without getting a response from
// all clients
this.network.kill();
viewNet.setDisable(true);
endNet.setDisable(true);
viewNetLog.setDisable(true);
newNet.setDisable(false);
});
viewNetLog.setOnAction(e -> {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Network Log");
alert.setHeaderText(null);
alert.setContentText(this.network.getLog().getLog());
alert.showAndWait();
});
network.getItems().addAll(newNet, viewNet, viewNetLog, endNet);
MenuItem newFract = new MenuItem("New Fractal");
newFract.setOnAction(e -> {
layerIndex = 1;
this.fractal = new RenderManager();
gradient.updateLayer(this.fractal.getLayers().get(0));
System.out.println(this.fractal.getLayers().get(0));
deleteLayers();
CheckBoxTreeItem i = getNewTreeItem();
layers.getRoot().getChildren().add(0, i);
this.updateFractalImage();
});
MenuItem openFract = new MenuItem("Open Fractal");
openFract.setOnAction(e -> {
FileChooser chooser = new FileChooser();
chooser.setTitle("Open Fractal");
chooser.setInitialDirectory(new File("fractals"));
FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter("Fractals (*.fractal)", "*.fractal");
chooser.getExtensionFilters().add(filter);
File f = chooser.showOpenDialog(null);
this.fractal = new RenderManager(f);
gradient.updateLayer(this.fractal.getLayers().get(0));
deleteLayers();
for (int k = 0; k < this.fractal.getLayers().size(); k++) {
Layer l = this.fractal.getLayers().get(k);
CheckBoxTreeItem i = getNewTreeItem();
MetaLayer meta = (MetaLayer) (i.getValue());
meta.setName(l.getName());
meta.setOpacity(l.getOpacity());
meta.setType(l.getClass().getSimpleName());
layers.getRoot().getChildren().add(0, i);
}
this.updateFractalImage();
});
MenuItem saveFract = new MenuItem("Save Fractal");
saveFract.setOnAction(e -> {
this.fractal.saveFractal();
});
MenuItem saveFractAs = new MenuItem("Save Fractal As");
saveFractAs.setOnAction(e -> {
this.fractal.saveFractalAs();
});
MenuItem exportFract = new MenuItem("Export Fractal");
exportFract.setOnAction(e -> {
ExportImageTool export = new ExportImageTool();
export.exportImage(this.fractal);
});
fractal.getItems().addAll(newFract, openFract, saveFract, saveFractAs, exportFract);
MenuItem newLayer = new MenuItem("New Layer Type");
newLayer.setOnAction(e -> {
RegisterLayerTool register = new RegisterLayerTool();
register.registerLayer();
Layer.registerLayer(register.getFile());
});
MenuItem help = new MenuItem("Help");
help.setOnAction(e -> {
ExpandableMenu.displayInformation("Help", "Instructions:", getHelpText());
});
system.getItems().addAll(newLayer, help);
menu.getMenus().addAll(fractal);
menu.getMenus().addAll(network);
menu.getMenus().addAll(system);
}
VBox center = new VBox();
center.getChildren().addAll(fractalView, fractalEditor);
trees.getChildren().addAll(parameters, layers, render);
bp.setCenter(center);
bp.setRight(trees);
// This is where the menu is located on the border pane
bp.setTop(menu);
bp.minWidthProperty().bind(this.widthProperty());
bp.minHeightProperty().bind(this.heightProperty());
render.minHeightProperty().bind(trees.minHeightProperty().subtract(fractalView.fitHeightProperty()));
fractalEditor.setContent(gradient);
fractalEditor.minHeight(200);
updateParams(0);
}
use of javafx.scene.control.TreeItem in project mybatis-generator-gui-extension by spawpaw.
the class DatabaseConfig method connect.
/**
* 连接数据库,初始化表信息
*/
public void connect() throws SQLException {
if (tableConfigs != null && tableConfigs.size() != 0)
return;
tableConfigs = new Hashtable<>();
if (tableNamePattern.getValue().isEmpty())
tableNamePattern.setValue("%");
Connection connection = getConnection();
DatabaseMetaData meta = connection.getMetaData();
ResultSet rs;
String _catalog = null;
String _schemaPattern = null;
String _tableNamePattern = null;
String[] types = { "TABLE", "VIEW" };
String sql;
// 获取表列表
switch(DatabaseType.valueOf(databaseType.getValue())) {
case MySQL:
_catalog = connection.getCatalog();
_schemaPattern = dbName.getValue().isEmpty() ? null : dbName.getValue();
_tableNamePattern = tableNamePattern.getValue();
rs = meta.getTables(_catalog, _schemaPattern, _tableNamePattern, types);
break;
case Oracle:
case Oracle_SID:
case Oracle_ServiceName:
case Oracle_TNSName:
case Oracle_TNSEntryString:
_catalog = null;
_schemaPattern = userName.getValue().toUpperCase();
_tableNamePattern = tableNamePattern.getValue();
rs = meta.getTables(_catalog, _schemaPattern, _tableNamePattern, types);
break;
case SQLServer:
case SQLServer_InstanceBased:
_catalog = dbName.getValue();
_tableNamePattern = tableNamePattern.getValue();
sql = "select name as TABLE_NAME from sysobjects where xtype='u' or xtype='v' ";
rs = connection.createStatement().executeQuery(sql);
break;
case PostgreSQL:
_catalog = null;
_schemaPattern = "%";
_tableNamePattern = tableNamePattern.getValue();
rs = meta.getTables(_catalog, _schemaPattern, _tableNamePattern, types);
break;
case DB2MF:
case DB2:
_catalog = null;
_schemaPattern = "jence_user";
_tableNamePattern = tableNamePattern.getValue();
rs = meta.getTables(_catalog, _schemaPattern, _tableNamePattern, types);
break;
case SYBASE:
_catalog = null;
_schemaPattern = null;
_tableNamePattern = tableNamePattern.getValue();
rs = meta.getTables(_catalog, _schemaPattern, _tableNamePattern, types);
break;
case INFORMIX:
_catalog = null;
_schemaPattern = null;
_tableNamePattern = tableNamePattern.getValue();
rs = meta.getTables(_catalog, _schemaPattern, _tableNamePattern, types);
break;
default:
throw new RuntimeException(Constants.getI18nStr("msg.unsupportedDatabase"));
}
while (rs.next()) {
tableConfigs.put(rs.getString("TABLE_NAME"), new ArrayList<>());
// 针对MYSQL,增加获取DDL的功能
if (DatabaseType.MySQL.equals(DatabaseType.valueOf(databaseType.getValue()))) {
ResultSet tableNameRs = connection.createStatement().executeQuery("SHOW CREATE TABLE " + rs.getString("TABLE_NAME") + ";");
while (tableNameRs.next()) {
if (existsColumn(tableNameRs, "table")) {
String tableName = tableNameRs.getString("table");
String tableDDL = tableNameRs.getString("create table");
tableDDLs.put(tableName, tableDDL);
log.info("table:{}; tableDDLs:{}", tableName, tableDDL);
} else if (existsColumn(tableNameRs, "view")) {
String viewName = tableNameRs.getString("view");
String viewDDL = tableNameRs.getString("create view");
tableDDLs.put(viewName, viewDDL);
log.info("viewName:{}; view DDL:{}", viewName, viewDDL);
} else {
log.error("the row is neither table nor view.");
}
}
}
}
List<String> tmpList = new ArrayList<>(tableConfigs.keySet());
tmpList.sort(Comparator.naturalOrder());
// 获取每个表中的字段信息
for (String tableName : tmpList) {
// 生成表的基本信息(每个字段的名称、类型)
rs = meta.getColumns(_catalog, _schemaPattern, tableName, null);
while (rs.next()) {
TableColumnMetaData columnMetaData = new TableColumnMetaData();
columnMetaData.setColumnName(rs.getString("COLUMN_NAME"));
columnMetaData.setJdbcType(rs.getString("TYPE_NAME"));
tableConfigs.get(tableName).add(columnMetaData);
}
// 生成TreeView
TreeItem<String> item = new TreeItem<>(tableName);
rootItem.getChildren().add(item);
rootItem.setExpanded(true);
}
connection.close();
}
use of javafx.scene.control.TreeItem in project jabref by JabRef.
the class GroupTreeController method initialize.
@FXML
public void initialize() {
viewModel = new GroupTreeViewModel(stateManager, dialogService, taskExecutor);
// Set-up groups tree
groupTree.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
// Set-up bindings
Consumer<ObservableList<GroupNodeViewModel>> updateSelectedGroups = (newSelectedGroups) -> newSelectedGroups.forEach(this::selectNode);
Consumer<List<TreeItem<GroupNodeViewModel>>> updateViewModel = (newSelectedGroups) -> {
if (newSelectedGroups == null) {
viewModel.selectedGroupsProperty().clear();
} else {
viewModel.selectedGroupsProperty().setAll(newSelectedGroups.stream().map(TreeItem::getValue).collect(Collectors.toList()));
}
};
BindingsHelper.bindContentBidirectional(groupTree.getSelectionModel().getSelectedItems(), viewModel.selectedGroupsProperty(), updateSelectedGroups, updateViewModel);
viewModel.filterTextProperty().bind(searchField.textProperty());
groupTree.rootProperty().bind(EasyBind.map(viewModel.rootGroupProperty(), group -> new RecursiveTreeItem<>(group, GroupNodeViewModel::getChildren, GroupNodeViewModel::expandedProperty, viewModel.filterPredicateProperty())));
// Icon and group name
mainColumn.setCellValueFactory(cellData -> cellData.getValue().valueProperty());
mainColumn.setCellFactory(new ViewModelTreeTableCellFactory<GroupNodeViewModel, GroupNodeViewModel>().withText(GroupNodeViewModel::getDisplayName).withIcon(GroupNodeViewModel::getIconCode, GroupNodeViewModel::getColor).withTooltip(GroupNodeViewModel::getDescription));
// Number of hits
PseudoClass anySelected = PseudoClass.getPseudoClass("any-selected");
PseudoClass allSelected = PseudoClass.getPseudoClass("all-selected");
numberColumn.setCellFactory(new ViewModelTreeTableCellFactory<GroupNodeViewModel, GroupNodeViewModel>().withGraphic(group -> {
final StackPane node = new StackPane();
node.getStyleClass().setAll("hits");
if (!group.isRoot()) {
BindingsHelper.includePseudoClassWhen(node, anySelected, group.anySelectedEntriesMatchedProperty());
BindingsHelper.includePseudoClassWhen(node, allSelected, group.allSelectedEntriesMatchedProperty());
}
Text text = new Text();
text.textProperty().bind(group.getHits().asString());
text.getStyleClass().setAll("text");
node.getChildren().add(text);
node.setMaxWidth(Control.USE_PREF_SIZE);
return node;
}));
// Arrow indicating expanded status
disclosureNodeColumn.setCellValueFactory(cellData -> cellData.getValue().valueProperty());
disclosureNodeColumn.setCellFactory(new ViewModelTreeTableCellFactory<GroupNodeViewModel, GroupNodeViewModel>().withGraphic(viewModel -> {
final StackPane disclosureNode = new StackPane();
disclosureNode.visibleProperty().bind(viewModel.hasChildrenProperty());
disclosureNode.getStyleClass().setAll("tree-disclosure-node");
final StackPane disclosureNodeArrow = new StackPane();
disclosureNodeArrow.getStyleClass().setAll("arrow");
disclosureNode.getChildren().add(disclosureNodeArrow);
return disclosureNode;
}).withOnMouseClickedEvent(group -> event -> group.toggleExpansion()));
// Set pseudo-classes to indicate if row is root or sub-item ( > 1 deep)
PseudoClass rootPseudoClass = PseudoClass.getPseudoClass("root");
PseudoClass subElementPseudoClass = PseudoClass.getPseudoClass("sub");
// Pseudo-classes for drag and drop
PseudoClass dragOverBottom = PseudoClass.getPseudoClass("dragOver-bottom");
PseudoClass dragOverCenter = PseudoClass.getPseudoClass("dragOver-center");
PseudoClass dragOverTop = PseudoClass.getPseudoClass("dragOver-top");
groupTree.setRowFactory(treeTable -> {
TreeTableRow<GroupNodeViewModel> row = new TreeTableRow<>();
row.treeItemProperty().addListener((ov, oldTreeItem, newTreeItem) -> {
boolean isRoot = newTreeItem == treeTable.getRoot();
row.pseudoClassStateChanged(rootPseudoClass, isRoot);
boolean isFirstLevel = (newTreeItem != null) && (newTreeItem.getParent() == treeTable.getRoot());
row.pseudoClassStateChanged(subElementPseudoClass, !isRoot && !isFirstLevel);
});
row.setDisclosureNode(null);
row.disclosureNodeProperty().addListener((observable, oldValue, newValue) -> row.setDisclosureNode(null));
row.contextMenuProperty().bind(EasyBind.monadic(row.itemProperty()).map(this::createContextMenuForGroup).orElse((ContextMenu) null));
row.setOnDragDetected(event -> {
TreeItem<GroupNodeViewModel> selectedItem = treeTable.getSelectionModel().getSelectedItem();
if ((selectedItem != null) && (selectedItem.getValue() != null)) {
Dragboard dragboard = treeTable.startDragAndDrop(TransferMode.MOVE);
dragboard.setDragView(row.snapshot(null, null));
ClipboardContent content = new ClipboardContent();
content.put(DragAndDropDataFormats.GROUP, selectedItem.getValue().getPath());
dragboard.setContent(content);
event.consume();
}
});
row.setOnDragOver(event -> {
Dragboard dragboard = event.getDragboard();
if ((event.getGestureSource() != row) && row.getItem().acceptableDrop(dragboard)) {
event.acceptTransferModes(TransferMode.MOVE, TransferMode.LINK);
removePseudoClasses(row, dragOverBottom, dragOverCenter, dragOverTop);
switch(getDroppingMouseLocation(row, event)) {
case BOTTOM:
row.pseudoClassStateChanged(dragOverBottom, true);
break;
case CENTER:
row.pseudoClassStateChanged(dragOverCenter, true);
break;
case TOP:
row.pseudoClassStateChanged(dragOverTop, true);
break;
}
}
event.consume();
});
row.setOnDragExited(event -> {
removePseudoClasses(row, dragOverBottom, dragOverCenter, dragOverTop);
});
row.setOnDragDropped(event -> {
Dragboard dragboard = event.getDragboard();
boolean success = false;
if (dragboard.hasContent(DragAndDropDataFormats.GROUP)) {
String pathToSource = (String) dragboard.getContent(DragAndDropDataFormats.GROUP);
Optional<GroupNodeViewModel> source = viewModel.rootGroupProperty().get().getChildByPath(pathToSource);
if (source.isPresent()) {
source.get().draggedOn(row.getItem(), getDroppingMouseLocation(row, event));
success = true;
}
}
if (dragboard.hasContent(DragAndDropDataFormats.ENTRIES)) {
TransferableEntrySelection entrySelection = (TransferableEntrySelection) dragboard.getContent(DragAndDropDataFormats.ENTRIES);
row.getItem().addEntriesToGroup(entrySelection.getSelection());
success = true;
}
event.setDropCompleted(success);
event.consume();
});
return row;
});
// Filter text field
setupClearButtonField(searchField);
}
use of javafx.scene.control.TreeItem in project Gargoyle by callakrsos.
the class PostgreSqlPane method menuExportMergeScriptOnAction.
/* (non-Javadoc)
* @see com.kyj.fx.voeditor.visual.component.sql.view.SqlPane#menuExportMergeScriptOnAction(javafx.event.ActionEvent)
*/
@Override
public void menuExportMergeScriptOnAction(ActionEvent e) {
// TableView<Map<String, Object>> tbResult = getTbResult();
List<Map<String, Object>> items = getSelectedTabResultItems();
// TreeView<DatabaseItemTree<String>> schemaTree = getSchemaTree();
//
// List<String> schemaList = schemaTree.getRoot().getChildren().stream().map(v -> v.getValue().getName()).collect(Collectors.toList());
//
String defaultSchema = "";
try {
Map<String, Object> findOne = DbUtil.findOne(connectionSupplier.get(), "select current_schema() as currentschema");
if (findOne != null && !findOne.isEmpty()) {
defaultSchema = ValueUtil.decode(findOne.get("currentschema"), "").toString();
}
} catch (Exception e4) {
e4.printStackTrace();
}
//
final String _defaultSchema = defaultSchema;
//
// if (items.isEmpty())
// return;
//
// // TODO :: DBMS에 따라 Merge문 생성 로직 분기 처리 필요.
//
// Optional<Pair<String, String[]>> showInputDialog = DialogUtil.showInputCustomDialog(tbResult.getScene().getWindow(), "table Name",
// "테이블명을 입력하세요.", new CustomInputDialogAction<GridPane, String[]>() {
//
// TextField txtSchema;
// TextField txtTable;
//
// @Override
// public GridPane getNode() {
// GridPane gridPane = new GridPane();
// txtSchema = new TextField();
// txtTable = new TextField();
//
// FxUtil.installAutoTextFieldBinding(txtSchema, () -> {
// return schemaList;
// });
//
// FxUtil.installAutoTextFieldBinding(txtTable, () -> {
// return searchPattern(txtSchema.getText(), txtTable.getText()).stream().map(v -> v.getValue().getName())
// .collect(Collectors.toList());
// });
// txtSchema.setText(_defaultSchema);
//
// //Default TableName
// TreeItem<DatabaseItemTree<String>> selectedItem = getSchemaTree().getSelectionModel().getSelectedItem();
// if (null != selectedItem) {
// DatabaseItemTree<String> value = selectedItem.getValue();
// if (value instanceof TableItemTree) {
// txtTable.setText(value.getName());
// }
// }
//
// Label label = new Label("Schema : ");
// Label label2 = new Label("Table : ");
// gridPane.add(label, 0, 0);
// gridPane.add(label2, 1, 0);
// gridPane.add(txtSchema, 0, 1);
// gridPane.add(txtTable, 1, 1);
// return gridPane;
// }
//
// @Override
// public String[] okClickValue() {
//
// String schema = txtSchema.getText().trim();
// String table = txtTable.getText().trim();
//
// String[] okValue = new String[2];
// okValue[0] = schema;
// okValue[1] = table;
// return okValue;
// }
//
// @Override
// public String[] cancelClickValue() {
// return null;
// }
//
// });
Optional<Pair<String, String[]>> showTableInputDialog = showTableInputDialog(v -> v.getName());
showTableInputDialog.ifPresent(op -> {
if (!"OK".equals(op.getKey()))
return;
String[] resultValue = op.getValue();
try {
StringBuilder clip = new StringBuilder();
PostgreTableItemTree dirtyTreeItem = new PostgreTableItemTree();
String schemaName = (resultValue[0] == null || resultValue[0].isEmpty()) ? _defaultSchema : resultValue[0];
String tableName = resultValue[1];
String childrenSQL = dirtyTreeItem.getChildrenSQL(schemaName, tableName);
List<Map<String, Object>> select = DbUtil.select(childrenSQL);
List<String> pkList = new ArrayList<>();
List<String> notPkList = new ArrayList<>();
List<String> columnList = new ArrayList<>();
for (Map<String, Object> map : select) {
String columnName = map.get("column_name").toString();
Object primaryKeyYn = map.get("primary_yn");
columnList.add(columnName);
if ("Y".equals(primaryKeyYn)) {
pkList.add(columnName);
} else {
notPkList.add(columnName);
}
}
String mergePreffix = String.format("with upsert as ( update %s set ", tableName);
String mergeMiddle = " returning * )\n";
String collect = columnList.stream().collect(Collectors.joining(", ", "(", ")"));
String insertPreffix = String.format("insert into %s", tableName);
String insertend = " where not exists (select * from upsert);\n";
List<String> valueList = items.stream().map(v -> {
return ValueUtil.toJSONObject(v);
}).map(v -> {
String updateSetSql = notPkList.stream().map(str -> {
if (str == null)
return null;
else {
JsonElement jsonElement = v.get(str);
if (jsonElement == null) {
return str.concat("=").concat("null");
} else {
String dataValue = jsonElement.toString();
dataValue = dataValue.substring(1, dataValue.length() - 1);
if (dataValue.indexOf("'") >= 0) {
dataValue = StringUtils.replace(dataValue, "'", "''");
}
return str.concat("=").concat("'").concat(dataValue).concat("'");
}
}
}).collect(Collectors.joining(", "));
String updateWhereSql = pkList.stream().map(str -> {
if (str == null)
return null;
else {
if (null == v.get(str))
return null;
String dataValue = v.get(str).toString();
dataValue = dataValue.substring(1, dataValue.length() - 1);
if (dataValue.indexOf("'") >= 0) {
try {
dataValue = StringUtils.replace(dataValue, "'", "''");
} catch (Exception e1) {
e1.printStackTrace();
}
}
return str.concat(" = ").concat("'").concat(dataValue).concat("'");
}
}).filter(str -> str != null).collect(Collectors.joining(" and "));
String insertValueSql = columnList.stream().map(str -> {
if (str == null)
return null;
else {
JsonElement jsonElement = v.get(str);
if (jsonElement == null) {
return "null";
} else {
String dataValue = jsonElement.toString();
dataValue = dataValue.substring(1, dataValue.length() - 1);
if (dataValue.indexOf("'") >= 0) {
dataValue = StringUtils.replace(dataValue, "'", "''");
}
return "'".concat(dataValue).concat("'");
}
}
}).collect(Collectors.joining(", "));
return new StringBuilder().append(mergePreffix).append(updateSetSql).append(" where ").append(updateWhereSql).append(mergeMiddle).append(insertPreffix).append(collect).append(" select ").append(insertValueSql).append(insertend).toString();
}).collect(Collectors.toList());
valueList.forEach(str -> {
clip.append(str);
});
SqlKeywords parent = new SqlKeywords();
{
MenuBar menuBar = new MenuBar();
Menu menuFile = new Menu("File");
MenuItem miSaveAs = new MenuItem("Save As");
miSaveAs.setOnAction(ev -> {
File saveAsFile = DialogUtil.showFileSaveCheckDialog(getScene().getWindow(), chooser -> {
chooser.getExtensionFilters().add(new ExtensionFilter(GargoyleExtensionFilters.SQL_NAME, GargoyleExtensionFilters.SQL));
});
if (saveAsFile != null) {
ThreadUtil.createNewThreadAndRun("Saveas", () -> {
SaveSQLFileFunction function = new SaveSQLFileFunction();
function.apply(saveAsFile, parent.getText());
});
}
});
menuFile.getItems().add(miSaveAs);
menuBar.getMenus().add(menuFile);
parent.setTop(menuBar);
}
parent.setContent(clip.toString());
parent.setWrapText(false);
parent.setPrefSize(1200d, 800d);
FxUtil.createStageAndShow(parent, stage -> {
stage.initOwner(getScene().getWindow());
stage.setTitle(String.format("[Merge Script] Table : %s", tableName));
});
} catch (Exception e2) {
LOGGER.error(ValueUtil.toString(e2));
DialogUtil.showExceptionDailog(e2, "에러발생, 테이블을 잘못 선택하셨을 수 있습니다.");
}
});
}
Aggregations