working on it ...

Filters

Explore Public Snippets

Sort by

Found 322 snippets matching: javafx

    public by gajendragusain  3695  35  4  0

    JavaFX dynamic tableview using MySQL

    This is a simple JavaFX frontend to manage your database
    /*
     * Created by gajendra on 8/28/2016.
     */
    
    import javafx.application.Application;
    import javafx.beans.property.SimpleStringProperty;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.geometry.Insets;
    import javafx.scene.Scene;
    import javafx.scene.control.*;
    import javafx.scene.control.TableColumn.CellDataFeatures;
    import javafx.scene.control.cell.TextFieldTableCell;
    import javafx.scene.layout.HBox;
    import javafx.scene.layout.StackPane;
    import javafx.scene.layout.VBox;
    import javafx.scene.paint.Color;
    import javafx.stage.Stage;
    import javafx.util.Callback;
    
    import java.sql.*;
    import java.util.ArrayList;
    
    public class App extends Application {
        private DbHelper db=DbHelper.getInstance();
        private TableView<ObservableList<String>> table;
        private ObservableList<ObservableList<String>> data;
        private Label query_status;
        private Label tableEditable;
        private Button add;
        private HBox dropdownHolder;
        private HBox radioBox;
        private VBox vbox;
        private ComboBox<String> databaseDropdown, tableDropdown;
        private TextArea queryBox;
        private Button submitQuery;
        private ToggleGroup radioGroup;
        private RadioButton r1,r2;
    
        public static void main(String[] args) {
            launch(args);
        }
    
        @Override
        public void start(Stage primaryStage) {
            initComponents();
    
            databaseDropdown.valueProperty().addListener(new ChangeListener<String>() {
    
                @Override
                public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                    tableDropdown.getItems().clear();
                    table.getItems().clear();
                    table.getColumns().clear();
                    query_status.setText("");
                    queryBox.clear();
                    db.setDB_URL(newValue);
                    getTables();
                }
            });
            
            tableDropdown.valueProperty().addListener(new ChangeListener<String>() {
    
                @Override
                public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {
                    table.getItems().clear();
                    table.getColumns().clear();
                    query_status.setText("");
                    queryBox.clear();
                    getData(newValue);
                }
            });
    
            submitQuery.setOnAction(new EventHandler<ActionEvent>() {
    
                @Override
                public void handle(ActionEvent event) {
                    table.getColumns().clear();
                    table.getItems().clear();
                    String query = queryBox.getText();
                    try{
                        Connection con = db.getConnection();
                        Statement s=con.createStatement();
                        if(r1.selectedProperty().getValue()) {
                            ResultSet rs = s.executeQuery(query);
                            populateTable(rs,false);
                            query_status.setText("Query Ok");
                            query_status.setTextFill(Color.GREEN);
                        }
                        else
                        {
                            if(s.executeUpdate(query)>0)
                            {
                                query_status.setText("Query Ok");
                                query_status.setTextFill(Color.GREEN);
                                String tableName = tableDropdown.getValue();
                                ResultSet rs =s.executeQuery("select *from "+tableName+"");
                                populateTable(rs,false);
                            }
                        }
                        s.close();
                        con.close();
                    }
                    catch(Exception e){
                        query_status.setText(e.toString());
                        query_status.setTextFill(Color.RED);
                        e.printStackTrace();
                    }
                }
            });
    
            getShemas();
            dropdownHolder.getChildren().addAll(databaseDropdown, tableDropdown,tableEditable);
            radioBox.getChildren().addAll(r1,r2,submitQuery);
            vbox.getChildren().addAll(dropdownHolder,table,query_status,queryBox,radioBox);
            StackPane stack =new StackPane();
            stack.getChildren().add(vbox);
            Scene scene = new Scene(stack);
            primaryStage.setScene(scene);
            primaryStage.show();
        }
        
        public void initComponents()
        {
            table=new TableView<>();
            table.setColumnResizePolicy(TableView.UNCONSTRAINED_RESIZE_POLICY);
            data = FXCollections.observableArrayList();
            dropdownHolder = new HBox();
            dropdownHolder.setSpacing(5);
            dropdownHolder.setPadding(new Insets(5,5,5,5));
            radioBox = new HBox();
            radioBox.setSpacing(10);
            radioBox.setPadding(new Insets(5,5,5,0));
            vbox = new VBox();
            vbox.setPadding(new Insets(5,5,5,5));;
            query_status = new Label();
            query_status.setPadding(new Insets(5,5,5,5));
            tableEditable = new Label();
            tableEditable.setPadding(new Insets(5,0,0,5));
            add = new Button("Add");
            databaseDropdown = new ComboBox<>();
            tableDropdown = new ComboBox<>();
            queryBox = new TextArea();
            queryBox.setPromptText("Enter your Custom Query here.");
            submitQuery = new Button("Submit Query");
            radioGroup = new ToggleGroup();
            r1= new RadioButton("Select Query");
            r2 = new RadioButton("Update queries: insert, update delete");
            r1.setToggleGroup(radioGroup);
            r2.setToggleGroup(radioGroup);
            r1.selectedProperty().setValue(true);
            r1.setPadding(new Insets(5,0,0,0));
            r2.setPadding(new Insets(5,0,0,0));
        }
    
        public ArrayList<String> getUniqueKeys(String tableName)
        {
            ArrayList<String> indexes = new ArrayList<>();
            try{
                Connection con = db.getConnection();
                DatabaseMetaData dbmd = con.getMetaData();
                ResultSet rs = dbmd.getIndexInfo(null,null,tableName,true,true);
                while(rs.next())
                {
                    System.out.println(rs.getString("COLUMN_NAME"));
                    indexes.add(rs.getString("COLUMN_NAME"));
                }
                rs.close();
                con.close();
            }catch(Exception e){
                e.printStackTrace();
            }
            return indexes;
        }
    
        public ArrayList<String> getTableMetaData(String tableName)
        {
            ArrayList<String> columnList =new ArrayList<>();
            try{
                Connection con = db.getConnection();
                Statement s=con.createStatement();
                ResultSet rs=s.executeQuery("select *from "+tableName);
                ResultSetMetaData rm = rs.getMetaData();
                for(int i=1;i<=rm.getColumnCount();i++)
                {
                    columnList.add(rm.getColumnName(i));
                }
                rs.close();
                s.close();
                con.close();
            }catch (Exception e){
                e.printStackTrace();
            }
            return columnList;
        }
    
        public void setEditable(TableColumn c)
        {
            c.setCellFactory(TextFieldTableCell.forTableColumn());
            c.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<ObservableList<String>,String>>() {
    
                @Override
                public void handle(TableColumn.CellEditEvent<ObservableList<String>,String> event) {
                    ObservableList<String> currentRow = event.getTableView().getItems().get(event.getTablePosition().getRow());
                    String oldval = event.getOldValue();
                    String newval = event.getNewValue();
                    String currentColumnName = event.getTableColumn().getText();
    
    //                System.out.println("id: "+currentColumnName);
                    int currentColumnIndex = event.getTableView().getColumns().indexOf(event.getTableColumn());
                    ArrayList<String> unique_indexes = getUniqueKeys(tableDropdown.getValue());
                    ArrayList<String> columnNames = getTableMetaData(tableDropdown.getValue());
                    int uniqueColumnIndex = columnNames.indexOf(unique_indexes.get(0));
                    String value = currentRow.get(uniqueColumnIndex);
                    if(updateTable(currentColumnName,unique_indexes.get(0),value,newval)>0)
                    {
                        currentRow.set(currentColumnIndex,newval);
                    }
                    else
                        currentRow.set(currentColumnIndex,oldval);
                }
            });
        }
    
        public int updateTable(String currentField, String uniqueColumnName, String uniqueColumnId, String newval)
        {
            int n=0;
            String tableName = tableDropdown.getValue();
            System.out.println("Table Name: "+tableName);
            try{
                Connection con=db.getConnection();
                Statement s=con.createStatement();
                String query = "update `"+tableName+"` set `"+currentField+"`='"+newval+"' where `"+uniqueColumnName+"`='"+uniqueColumnId+"'";
                query_status.setText(query+" ; Query Ok");
                query_status.setTextFill(Color.GREEN);
                System.out.println("UPdate Query: "+query);
                n=s.executeUpdate(query);
                s.close();
                con.close();
            }
            catch(Exception e){
                query_status.setText(e.toString());
                query_status.setTextFill(Color.RED);
                e.printStackTrace();
            }
            System.out.println("n: "+n);
            return n;
        }
    
        public void getTables()
        {
            try{
                Connection con=db.getConnection();
    
                DatabaseMetaData dmd= con.getMetaData();
    
                ResultSet rs=dmd.getTables(null,null,null,null);
    
                while(rs.next())
                {
                    System.out.println(rs.getString("TABLE_NAME"));
                    tableDropdown.getItems().add(rs.getString("TABLE_NAME"));
                }
                tableDropdown.setPromptText("Select a Table");
    //            tableDropdown.setValue(tableDropdown.getItems().get(0));
                rs.close();
                con.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    
        public void getShemas()
        {
            try{
                Connection con=db.getConnection();
                DatabaseMetaData dmd= con.getMetaData();
                ResultSet rs=dmd.getCatalogs();
                while(rs.next())
                {
                    System.out.println(rs.getString(1));
                    databaseDropdown.getItems().add(rs.getString(1));
                }
    //            databaseDropdown.setValue(databaseDropdown.getItems().get(0));
                databaseDropdown.setPromptText("Select a Database");
                rs.close();
                con.close();
            }catch(Exception e){
                e.printStackTrace();
            }
        }
    
        public void getData(String tableName)
        {
            data.clear();
            try{
                Connection con=db.getConnection();
                Statement s=con.createStatement();
                ResultSet r=s.executeQuery("select *from "+tableName);
                populateTable(r,true);
                s.close();
                con.close();
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    
        public void populateTable(ResultSet r, boolean isEditable)
        {
            if(isEditable)
            {
                table.setEditable(true);
                tableEditable.setText("Table is Editable: You can make changes in a Table-Cell by double-clicking on it.");
                tableEditable.setTextFill(Color.GREEN );
            }
            else
            {
                table.setEditable(false);
                tableEditable.setText("Table is not Editable");
                tableEditable.setTextFill(Color.RED);
            }
            ResultSetMetaData rm = null;
            try {
                rm = r.getMetaData();
                for(int i=0 ; i<rm.getColumnCount(); i++) {
    
                    //We are using non property style for making dynamic table
                    final int k = i;
                    String columnName = rm.getColumnName(i+1);
                    System.out.println(columnName);
                    TableColumn col = new TableColumn(columnName);
    
                    // Reference: http://blog.ngopal.com.np/2011/10/19/dyanmic-tableview-data-from-database/comment-page-1/
                    col.setCellValueFactory(new Callback<CellDataFeatures<ObservableList, String>, ObservableValue<String>>() {
                        public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) {
                            return new SimpleStringProperty(param.getValue().get(k).toString());
                        }
                    });
    
                    table.getColumns().add(col);
                    setEditable(col);
                }
                while(r.next())
                {
                    ObservableList<String> tableRow = FXCollections.observableArrayList();
    
                    for(int i=1;i<=rm.getColumnCount();i++)
                    {
                        String val = String.valueOf(r.getString(i));    // safeguards against null exceptions
                        String str=(String.valueOf(r.getString(i)).equals("null"))?"":r.getString(i);
                        System.out.println(str);
                        tableRow.add(str);
                    }
                    data.add(tableRow);
                }
                table.setItems(data);
                r.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    
    
    
    
    /* 
      DBhelper Class
      make sure you have appropriate jdbc driver in your classpath; mine is mysql jdbc
    */
      
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    /**
     * Created by gajendra on 8/25/2016.
     */
    public class DbHelper {
        private static final String DRIVER = "com.mysql.jdbc.Driver";
        private static final String URL = "jdbc:mysql://localhost/";
        private static String DB_URL=URL;
        private static final String USER = "root";
        private static final String PASS = "";
        private static Connection con;
        private static DbHelper helper = new DbHelper();
        private DbHelper()
        {
    
        }
    
        public static void setDB_URL(String url)
        {
            DB_URL=URL+url;
        }
        public static String getDB_URL()
        {
            return DB_URL;
        }
        public static DbHelper getInstance()
        {
            return helper;
        }
    
        protected static Connection getConnection()
        {
            try{
                Class.forName(DRIVER);
                con = DriverManager.getConnection(DB_URL,USER,PASS);
            }
            catch(ClassNotFoundException e){
                e.printStackTrace();
            }
            catch(Exception e){
                e.printStackTrace();
            }
    
            return con;
        }
    }
                                                

    public by michaelbukachi  1446  3  6  0

    JavaFx message dialog

    A utility method to show a message dialog using java fx
    private void showMessageDialog(String message) {
        	Alert alert = new Alert(AlertType.INFORMATION);
    		alert.setTitle("Confirm Action");
    		alert.setHeaderText(null);
    		alert.setContentText(message);
    		alert.show();
    	}

    public by michaelbukachi  1032  0  6  0

    Javafx confirmation dialog

    Utility method to show a confirmation dialog using javafx
    private boolean showConfirmationDialog(String message) {
    		Alert alert = new Alert(AlertType.CONFIRMATION);
    		alert.setTitle("Confirm Action");
    		alert.setHeaderText(null);
    		alert.setContentText(message);
    		Optional<ButtonType> result = alert.showAndWait();
    		
    		return result.get() == ButtonType.OK;
    	}

    external by piumnl  19  0  1  0

    [JavaFX 对话框及弹出框] JavaFX 对话框及弹出框 #javafx

    [JavaFX 对话框及弹出框] JavaFX 对话框及弹出框 #javafx: AlertExample.java
    import java.io.PrintWriter;
    import java.io.StringWriter;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Optional;
    
    import javafx.application.Application;
    import javafx.application.Platform;
    import javafx.event.EventHandler;
    import javafx.geometry.Insets;
    import javafx.scene.Node;
    import javafx.scene.Scene;
    import javafx.scene.control.Alert;
    import javafx.scene.control.Button;
    import javafx.scene.control.ButtonBar;
    import javafx.scene.control.ButtonType;
    import javafx.scene.control.ChoiceDialog;
    import javafx.scene.control.Dialog;
    import javafx.scene.control.Label;
    import javafx.scene.control.PasswordField;
    import javafx.scene.control.TextArea;
    import javafx.scene.control.TextField;
    import javafx.scene.control.TextInputDialog;
    import javafx.scene.image.Image;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.layout.FlowPane;
    import javafx.scene.layout.GridPane;
    import javafx.scene.layout.Priority;
    import javafx.stage.Stage;
    import javafx.util.Pair;
    
    public class AlertExample extends Application {
    
        @Override
        public void start(Stage primaryStage) throws Exception {
            FlowPane root = new FlowPane();
    
            root.getChildren().add(newButton("提示信息", event -> newBaseAlert()));
            root.getChildren().add(newButton("简单信息", event -> newNoHeadAlert()));
            root.getChildren().add(newButton("警告信息", event -> newWarningAlert()));
            root.getChildren().add(newButton("错误信息", event -> newErrorAlert()));
            root.getChildren().add(newButton("异常信息", event -> newExceptionAlert()));
            root.getChildren().add(newButton("确认对话框", event -> newReokAlert()));
            root.getChildren().add(newButton("自定义按钮", event -> newCustomAlert()));
            root.getChildren().add(newButton("文本框输入", event -> newInputDialog()));
            root.getChildren().add(newButton("选择对话框", event -> newChoiceDialog()));
            root.getChildren().add(newButton("自定义内容", event -> newCustomDialog()));
    
            primaryStage.setTitle("alert");
            primaryStage.setScene(new Scene(root, 400, 300));
            primaryStage.show();
    
        }
    
        private Button newButton(String name, EventHandler<? super MouseEvent> value) {
            Button btn = new Button(name);
            btn.setOnMouseClicked(value);
            return btn;
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    
        private void newBaseAlert() {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("信息提示对话框");
            alert.setHeaderText("头部内容");
            alert.setContentText("文本内容");
            alert.showAndWait();
        }
    
        private void newNoHeadAlert() {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("信息提示对话框");
            alert.setHeaderText(null);
            alert.setContentText("文本内容");
            alert.showAndWait();
        }
    
        private void newWarningAlert() {
            Alert alert = new Alert(Alert.AlertType.WARNING);
            alert.setTitle("警告对话框");
            alert.setHeaderText("头部内容");
            alert.setContentText("文本内容");
            alert.showAndWait();
        }
    
        private void newErrorAlert() {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("错误提示对话框");
            alert.setHeaderText("头部内容");
            alert.setContentText("文本内容");
            alert.showAndWait();
        }
    
        private void newExceptionAlert() {
            Alert alert = new Alert(Alert.AlertType.ERROR);
            alert.setTitle("异常堆栈对话框");
            alert.setHeaderText("头部内容");
            alert.setContentText("文本内容");
    
            Exception ex = new ClassNotFoundException("找不到类");
    
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            ex.printStackTrace(pw);
            String exceptionText = sw.toString();
    
            Label label = new Label("异常堆栈信息为:");
    
            TextArea textArea = new TextArea(exceptionText);
            textArea.setEditable(false);
            textArea.setWrapText(true);
    
            textArea.setMaxWidth(Double.MAX_VALUE);
            textArea.setMaxHeight(Double.MAX_VALUE);
            GridPane.setVgrow(textArea, Priority.ALWAYS);
            GridPane.setHgrow(textArea, Priority.ALWAYS);
    
            GridPane expContent = new GridPane();
            expContent.setMaxWidth(Double.MAX_VALUE);
            expContent.add(label, 0, 0);
            expContent.add(textArea, 0, 1);
    
            alert.getDialogPane().setExpandableContent(expContent);
    
            alert.showAndWait();
        }
    
        private void newReokAlert() {
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("确认信息对话框");
            alert.setHeaderText("确认退出");
            alert.setContentText("确认退出?");
    
            Optional<ButtonType> result = alert.showAndWait();
            if (result.isPresent() && result.get() == ButtonType.OK) {
                System.exit(0);
            }
        }
    
        private void newCustomAlert() {
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("自定义按钮的确认信息对话框");
            alert.setHeaderText("头部内容");
            alert.setContentText("文本内容");
    
            ButtonType btnType1 = new ButtonType("1");
            ButtonType btnType2 = new ButtonType("2");
            ButtonType btnType3 = new ButtonType("3");
            ButtonType btnType4 = new ButtonType("取消", ButtonBar.ButtonData.CANCEL_CLOSE);
    
            alert.getButtonTypes().setAll(btnType1, btnType2, btnType3, btnType4);
    
            Optional<ButtonType> result = alert.showAndWait();
            result.ifPresent(buttonType -> {
                if (buttonType == btnType1) {
                    System.out.println("点击了 1");
                } else if (buttonType == btnType2) {
                    System.out.println("点击了 2");
                } else if (buttonType == btnType3) {
                    System.out.println("点击了 3");
                } else {
                    System.out.println("点击了取消");
                }
            });
        }
    
        private void newInputDialog() {
            TextInputDialog dialog = new TextInputDialog("默认值");
            dialog.setTitle("文本输入对话框");
            dialog.setHeaderText("头部内容");
            dialog.setContentText("文本内容");
    
            Optional<String> result = dialog.showAndWait();
            result.ifPresent(value -> System.out.println("输入了" + value));
        }
    
        private void newChoiceDialog() {
            List<String> choices = new ArrayList<>();
            choices.add("Java");
            choices.add("Python");
            choices.add("JavaScript");
    
            ChoiceDialog<String> dialog = new ChoiceDialog<>("Python", choices);
            dialog.setTitle("选择对话框");
            dialog.setHeaderText("头部内容");
            dialog.setContentText("文本内容");
    
            Optional<String> result = dialog.showAndWait();
            result.ifPresent(value -> System.out.println("选择了" + value));
        }
    
    
        private void newCustomDialog() {
            Dialog<Pair<String, String>> dialog = new Dialog<>();
            dialog.setTitle("自定义对话框");
            dialog.setHeaderText("头部内容");
    
            // 设置头部图片
            // dialog.setGraphic(new ImageView(this.getClass().getResource("favicon64-w.png").toString()));
    
            ButtonType loginButtonType = new ButtonType("登录", ButtonBar.ButtonData.OK_DONE);
            dialog.getDialogPane().getButtonTypes().addAll(loginButtonType, ButtonType.CANCEL);
    
            GridPane grid = new GridPane();
            grid.setHgap(10);
            grid.setVgap(10);
            grid.setPadding(new Insets(20, 150, 10, 10));
    
            TextField name = new TextField();
            name.setPromptText("用户名");
            PasswordField password = new PasswordField();
            password.setPromptText("密码");
    
            grid.add(new Label("用户名:"), 0, 0);
            grid.add(name, 1, 0);
            grid.add(new Label("密码:"), 0, 1);
            grid.add(password, 1, 1);
    
            Node loginButton = dialog.getDialogPane().lookupButton(loginButtonType);
            loginButton.setDisable(true);
    
            // 是哟功能 Java 8 lambda 表达式进行校验
            name.textProperty().addListener((observable, oldValue, newValue) -> loginButton.setDisable(newValue.trim().isEmpty() || password.getText().trim().isEmpty()));
    
            password.textProperty().addListener((observable, oldValue, newValue) -> loginButton.setDisable(newValue.trim().isEmpty() || name.getText().trim().isEmpty()));
    
            dialog.getDialogPane().setContent(grid);
    
            // 默认光标在用户名上
            Platform.runLater(name::requestFocus);
    
            // 登录按钮后,将结果转为username-password-pair
            dialog.setResultConverter(dialogButton -> {
                if (dialogButton == loginButtonType) {
                    return new Pair<>(name.getText(), password.getText());
                }
                return null;
            });
    
            Optional<Pair<String, String>> result = dialog.showAndWait();
    
            result.ifPresent(usernamePwd -> System.out.println(usernamePwd.getKey() + " : " + usernamePwd.getValue()));
        }
    
        /**
         * 自定义icon图标
         */
        private void newCustomIconStage() {
            Dialog<Pair<String, String>> dialog = new Dialog<>();
    
            // 设置对话框拥有者
            // dialog.initOwner(parentWindow);
            // 设置模态
            // dialog.initModality(Modality.NONE);
    
            Stage stage = (Stage) dialog.getDialogPane().getScene().getWindow();
    
            stage.getIcons().add(new Image(this.getClass().getResource("favicon64-w.png").toString()));
        }
    }
    
    

    external by chrisduran  612  5  3  0

    Implementation of embedding the JavaFX webview within the Swing UI framework. From the following example: http://docs.oracle.com/javafx/2/swing/swing-fx-interoperability.htm#CHDIEEJE

    Implementation of embedding the JavaFX webview within the Swing UI framework. From the following example: http://docs.oracle.com/javafx/2/swing/swing-fx-interoperability.htm#CHDIEEJE: SimpleSwingBrowser.java
    package com.biomatters.sandbox;
    
    import javafx.application.Platform;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.embed.swing.JFXPanel;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.web.WebEngine;
    import javafx.scene.web.WebEvent;
    import javafx.scene.web.WebView;
    
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.MalformedURLException;
    import java.net.URL;
    
    import static javafx.concurrent.Worker.State.FAILED;
    
    public class SimpleSwingBrowser extends JFrame {
    
        private final JFXPanel jfxPanel = new JFXPanel();
        private WebEngine engine;
    
        private final JPanel panel = new JPanel(new BorderLayout());
        private final JLabel lblStatus = new JLabel();
    
    
        private final JButton btnGo = new JButton("Go");
        private final JTextField txtURL = new JTextField();
        private final JProgressBar progressBar = new JProgressBar();
    
        public SimpleSwingBrowser() {
            super();
            initComponents();
        }
    
    
        private void initComponents() {
            createScene();
    
            ActionListener al = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    loadURL(txtURL.getText());
                }
            };
    
            btnGo.addActionListener(al);
            txtURL.addActionListener(al);
    
            progressBar.setPreferredSize(new Dimension(150, 18));
            progressBar.setStringPainted(true);
    
            JPanel topBar = new JPanel(new BorderLayout(5, 0));
            topBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
            topBar.add(txtURL, BorderLayout.CENTER);
            topBar.add(btnGo, BorderLayout.EAST);
    
            JPanel statusBar = new JPanel(new BorderLayout(5, 0));
            statusBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
            statusBar.add(lblStatus, BorderLayout.CENTER);
            statusBar.add(progressBar, BorderLayout.EAST);
    
            panel.add(topBar, BorderLayout.NORTH);
            panel.add(jfxPanel, BorderLayout.CENTER);
            panel.add(statusBar, BorderLayout.SOUTH);
    
            getContentPane().add(panel);
    
            setPreferredSize(new Dimension(1024, 600));
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            pack();
    
        }
    
        private void createScene() {
    
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
    
                    WebView view = new WebView();
                    engine = view.getEngine();
    
                    engine.titleProperty().addListener(new ChangeListener<String>() {
                        @Override
                        public void changed(ObservableValue<? extends String> observable, String oldValue, final String newValue) {
                            SwingUtilities.invokeLater(new Runnable() {
                                @Override
                                public void run() {
                                    SimpleSwingBrowser.this.setTitle(newValue);
                                }
                            });
                        }
                    });
    
                    engine.setOnStatusChanged(new EventHandler<WebEvent<String>>() {
                        @Override
                        public void handle(final WebEvent<String> event) {
                            SwingUtilities.invokeLater(new Runnable() {
                                @Override
                                public void run() {
                                    lblStatus.setText(event.getData());
                                }
                            });
                        }
                    });
    
                    engine.locationProperty().addListener(new ChangeListener<String>() {
                        @Override
                        public void changed(ObservableValue<? extends String> ov, String oldValue, final String newValue) {
                            SwingUtilities.invokeLater(new Runnable() {
                                @Override
                                public void run() {
                                    txtURL.setText(newValue);
                                }
                            });
                        }
                    });
    
                    engine.getLoadWorker().workDoneProperty().addListener(new ChangeListener<Number>() {
                        @Override
                        public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, final Number newValue) {
                            SwingUtilities.invokeLater(new Runnable() {
                                @Override
                                public void run() {
                                    progressBar.setValue(newValue.intValue());
                                }
                            });
                        }
                    });
    
                    engine.getLoadWorker()
                            .exceptionProperty()
                            .addListener(new ChangeListener<Throwable>() {
    
                                public void changed(ObservableValue<? extends Throwable> o, Throwable old, final Throwable value) {
                                    if (engine.getLoadWorker().getState() == FAILED) {
                                        SwingUtilities.invokeLater(new Runnable() {
                                            @Override public void run() {
                                                JOptionPane.showMessageDialog(
                                                        panel,
                                                        (value != null) ?
                                                                engine.getLocation() + "\n" + value.getMessage() :
                                                                engine.getLocation() + "\nUnexpected error.",
                                                        "Loading error...",
                                                        JOptionPane.ERROR_MESSAGE);
                                            }
                                        });
                                    }
                                }
                            });
    
                    jfxPanel.setScene(new Scene(view));
                }
            });
        }
    
        public void loadURL(final String url) {
            Platform.runLater(new Runnable() {
                @Override
                public void run() {
                    String tmp = toURL(url);
    
                    if (tmp == null) {
                        tmp = toURL("http://" + url);
                    }
    
                    engine.load(tmp);
                }
            });
        }
    
        private static String toURL(String str) {
            try {
                return new URL(str).toExternalForm();
            } catch (MalformedURLException exception) {
                return null;
            }
        }
    
    
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
    
                public void run() {
                    SimpleSwingBrowser browser = new SimpleSwingBrowser();
                    browser.setVisible(true);
                    browser.loadURL("http://goo.gl/maps/GPXlp");
                }
            });
        }
    }
    
    

    external by Seungdols(Seungdols Company)  92  0  1  0

    JavaFX - LoginForm ref : http://docs.oracle.com/javafx/2/get_started/Login.java.html

    JavaFX - LoginForm ref : http://docs.oracle.com/javafx/2/get_started/Login.java.html: JavaFxLoginForm.java
    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package login;
    
    
    import javafx.application.Application;
    
    import javafx.geometry.Pos;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.PasswordField;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.GridPane;
    import javafx.scene.layout.HBox;
    
    import javafx.scene.paint.Color;
    import javafx.scene.text.Font;
    
    import javafx.scene.text.FontWeight;
    import javafx.scene.text.Text;
    import javafx.stage.Stage;
    
    /**
     *
     * @author Administrator
     */
    public class Login extends Application {
    
        @Override
        public void start(Stage primaryStage) {
            primaryStage.setTitle("Hello World!");
    
            GridPane grid = new GridPane();//그리드 패널 생성
            grid.setAlignment(Pos.CENTER);//가운데 정렬
            grid.setHgap(10);
            grid.setVgap(10);
            grid.setPadding(new javafx.geometry.Insets(25, 25, 25, 25));//상하좌우 간격 25픽셀
    
            Scene scene = new Scene(grid, 300, 275);
            primaryStage.setScene(scene);
            Text sceneTitle = new Text("Welcome PManager");
            sceneTitle.setFont(Font.font("Malgun Gothic", FontWeight.NORMAL, 20));
            grid.add(sceneTitle, 0, 0, 2, 1);
    
            javafx.scene.control.Label userName = new javafx.scene.control.Label("User Name : ");
            grid.add(userName, 0, 1);
    
            TextField userTField = new TextField();
            grid.add(userTField, 1, 1);
    
            javafx.scene.control.Label pw = new javafx.scene.control.Label("Password : ");
            grid.add(pw, 0, 2);
    
            PasswordField pwBox = new PasswordField();
            grid.add(pwBox, 1, 2);
    
            Button btn = new Button("Log in");
            Button signBtn = new Button("Sign Up");
            HBox hbBtn = new HBox(10);
            hbBtn.setAlignment(Pos.BOTTOM_RIGHT);
            hbBtn.getChildren().add(btn);
            grid.add(hbBtn, 1, 4);
            HBox hbSignBtn = new HBox(10);
            hbSignBtn.setAlignment(Pos.BOTTOM_LEFT);
            hbSignBtn.getChildren().add(signBtn);
            grid.add(hbSignBtn, 0, 4);
    
            final Text actionTarget = new Text();
            grid.add(actionTarget, 1, 6);
            btn.setOnAction(e -> {
                actionTarget.setFill(Color.FIREBRICK);
                actionTarget.setText("Log in");
            });
    
            primaryStage.show();
        }
    
        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            launch(args);
        }
    
    }
    
    
    

    external by Bryce Davis  194  0  2  0

    JavaFX Introductory Example

    JavaFX Introductory Example: ClickCounter.java
    import javafx.application.*;
    import javafx.stage.*;
    import javafx.scene.*;
    import javafx.scene.layout.*;
    import javafx.scene.control.*;
    
    public class ClickCounter extends Application
    {
        private static Button btn;
        private static Label lbl;
        private static int clickCount = 0;
        
        public static void main(String[] args)
        {
            launch(args);
        }
        
        @Override
        public void start(Stage primaryStage)
        {
            btn = new Button();
            btn.setText("Click me please!");
            btn.setOnAction(e -> buttonClick());
            
            lbl = new Label();
            lbl.setText("You have not clicked the button.");
            
            BorderPane pane = new BorderPane();
            pane.setTop(lbl);
            pane.setCenter(btn);
            
            Scene scene = new Scene(pane, 250, 150);
            
            primaryStage.setScene(scene);
            primaryStage.setTitle("Click Counter");
            primaryStage.show();
        }
        
        public void buttonClick()
        {
            clickCount++;
            if (clickCount == 1) {
                lbl.setText("You've clicked the button once.");
            } else {
                lbl.setText("You've clicked the button " + clickCount + " times.");
            }
        }
    }
    
    

    external by Eby Sofyan Fadly  160  0  2  0

    JavaFX TableModel

    JavaFX TableModel : TableModel.java
    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */
    package com.eby.book;
    
    import com.eby.helper.ListConverter;
    import com.eby.orm.entity.Book;
    import com.eby.orm.entity.Category;
    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.List;
    import java.util.Set;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    import javafx.scene.control.Label;
    import javafx.scene.control.TableCell;
    import javafx.scene.control.TableColumn;
    import javafx.scene.control.cell.PropertyValueFactory;
    import javafx.util.Callback;
    
    /**
     *
     * @author 3b1
     */
    public class BookTableModel {
    
        private List<Book> list;
        private ObservableList<Book> row;
        private Collection<TableColumn<Book, String>> column;
    
        public BookTableModel() {
            list = new ArrayList<Book>();
            row = FXCollections.observableArrayList(list);
            column = new ArrayList<TableColumn<Book, String>>();
            this.initColumn();
    
        }
    
        private void initColumn() {
            column.add(this.addTableColumn("ID", "id"));
            column.add(this.addTableColumn("TITLE", "title"));
            column.add(this.addTableColumn("SYNOPSIS", "synopsis"));
            column.add(this.addTableColumn("PUBLISHER", "publisher"));
            column.add(this.addTableColumn("AUTHOR", "author"));
            column.add(this.getCategory());
        }
    
        private TableColumn addTableColumn(String tableHeader, String entityAttribute) {
            TableColumn t = new TableColumn(tableHeader);
            t.setCellValueFactory(new PropertyValueFactory<Book, String>(entityAttribute));
            return t;
        }
    
        private TableColumn getCategory() {
            TableColumn t = this.addTableColumn("CATEGORY", "categories");
            t.setCellFactory(new Callback< TableColumn<Book, Set>, TableCell<Book, Set>>() {
    
                @Override
                public TableCell<Book, Set> call(TableColumn<Book, Set> param) {
                    TableCell<Book, Set> bookcatCell = new TableCell<Book, Set>() {
    
                        protected void updateItem(Set set, boolean empty) {
                            if (set != null) {
                                String out = "";
                                Iterator<Category> iter = set.iterator();
                                while (iter.hasNext()) {
                                    out = out + iter.next().getName() + ", ";
                                }
                                Label label = new Label(out);
                                setGraphic(label);
    
                            }
                        }
                    };
                    return bookcatCell;
                }
            ;
            });
             
             return t;
        }
    
        public Collection<TableColumn<Book, String>> getAllColumn() {
            return column;
        }
    
        public ObservableList<Book> getItem() {
            return row;
        }
    
    }
    
    
    

    external by Ondrej Kvasnovsky  2400  134  3  0

    Remove shadow from TextArea in JavaFX 8

    Remove shadow from TextArea in JavaFX 8: app.css
    .text-area {
        -fx-background-insets: 0;
        -fx-background-color: transparent, white, transparent, white;
        -fx-background-radius: 0, 0, 0, 0;
    
        -fx-box-border: none;
        -fx-focus-color: -fx-control-inner-background;
        -fx-faint-focus-color: -fx-control-inner-background;
        -fx-text-box-border: -fx-control-inner-background;
        -fx-border-width: -1;
    }
    
    .text-area .content {
        -fx-background-color: transparent, white, transparent, white;
    }
    
    .text-area:focused .content {
        -fx-background-color: transparent, white, transparent, white;
    }
    
    .scroll-pane {
    }
    
    .viewport {
        -fx-background-insets: 0;
        -fx-background-color: transparent, white, transparent, white;
        -fx-background-radius: 0, 0, 0, 0;
    
        -fx-focus-color: -fx-control-inner-background;
        -fx-faint-focus-color: -fx-control-inner-background;
        -fx-text-box-border: -fx-control-inner-background;
        -fx-border-width: -1;
    }
    
    .content {
    }
    
    .text {
    }
    
    .text-area:focused {
        -fx-highlight-fill: #7ecfff;
    
        -fx-background-insets: 0;
        -fx-background-color: transparent, white, transparent, white;
        -fx-background-radius: 0, 0, 0, 0;
    
        -fx-focus-color: -fx-control-inner-background;
        -fx-faint-focus-color: -fx-control-inner-background;
        -fx-text-box-border: -fx-control-inner-background;
        -fx-border-width: -1;
    }
    
    

    external by Thierry Wasylczenko  5668  91  5  0

    A trick to hide the tab area in a JavaFX TabPane when only one tab is present

    A trick to hide the tab area in a JavaFX TabPane when only one tab is present: gistfile1.java
    final TabPane pane = new TabPane();
    pane.getTabs().addListener((ListChangeListener) change -> {
      final  StackPane header = (StackPane) pane.lookup(".tab-header-area");
      
      if(header != null) {
        if(this.openedPresentationsTabPane.getTabs().size() == 1) header.setPrefHeight(0);
        else header.setPrefHeight(-1);
      }
    });
    
    
    • Public Snippets
    • Channels Snippets