2018년 9월 21일 금요일

[JavaFx] RingChart Image Generation


1. RingChart



AppRingChart.java


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.collections.*;
import javafx.scene.Scene;
import javafx.scene.chart.PieChart;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class AppRingChart extends Application {

    @Override public void start(Stage stage) {
        stage.setTitle("Imported Fruits");
        stage.setWidth(500);
        stage.setHeight(500);

        ObservableList<PieChart.Data> pieChartData = createData();
        pieChartData.forEach(e -> e.nameProperty().bind(Bindings.concat( e.getName(), " (", e.pieValueProperty(), ")")));

        final FxRingChart chart = new FxRingChart(pieChartData);
        chart.setTitle("Imported Fruits");

        Scene scene = new Scene(new StackPane(chart));
        stage.setScene(scene);
        stage.show();
    }

    private ObservableList<PieChart.Data> createData() {
        return FXCollections.observableArrayList(
                new PieChart.Data("Grapefruit", 13),
                new PieChart.Data("Oranges", 25),
                new PieChart.Data("Plums", 10),
                new PieChart.Data("Pears", 22),
                new PieChart.Data("Apples", 30));
    }

    public static void main(String[] args) {
        launch(args);
    }
}


RingChart.java


1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import javafx.collections.ObservableList;
import javafx.geometry.Bounds;
import javafx.scene.Node;
import javafx.scene.chart.PieChart;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;

public class FxRingChart extends PieChart {
    private final Circle innerCircle;

    public FxRingChart(ObservableList<Data> pieData) {
        super(pieData);
        innerCircle = new Circle();
        //innerCircle.setFill(new ImagePattern(yourImage))
        innerCircle.setFill(Color.WHITESMOKE);
        innerCircle.setStroke(Color.WHITE);
        innerCircle.setStrokeWidth(3);
    }

    @Override
    protected void layoutChartChildren(double top, double left, double contentWidth, double contentHeight) {
        super.layoutChartChildren(top, left, contentWidth, contentHeight);
        addInnerCircleIfNotPresent();
        updateInnerCircleLayout();
    }

    private void addInnerCircleIfNotPresent() {
        if (getData().size() > 0) {
            Node pie = getData().get(0).getNode();
            if (pie.getParent() instanceof Pane) {
                Pane parent = (Pane) pie.getParent();
                if (!parent.getChildren().contains(innerCircle)) {
                    parent.getChildren().add(innerCircle);
                }
            }
        }
    }

    private void updateInnerCircleLayout() {
        double minX = Double.MAX_VALUE, minY = Double.MAX_VALUE;
        double maxX = Double.MIN_VALUE, maxY = Double.MIN_VALUE;
        for (PieChart.Data data: getData()) {
            Node node = data.getNode();
            Bounds bounds = node.getBoundsInParent();
            if (bounds.getMinX() < minX) {
                minX = bounds.getMinX();
            }
            if (bounds.getMinY() < minY) {
                minY = bounds.getMinY();
            }
            if (bounds.getMaxX() > maxX) {
                maxX = bounds.getMaxX();
            }
            if (bounds.getMaxY() > maxY) {
                maxY = bounds.getMaxY();
            }
        }
        innerCircle.setCenterX(minX + (maxX - minX) / 2);
        innerCircle.setCenterY(minY + (maxY - minY) / 2);
        innerCircle.setRadius((maxX - minX) / 4);
    }
}





2018년 9월 15일 토요일

[JavaFx] MenuButton Example


1. MenuButton




Source Code:
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.MenuButton;
import javafx.scene.control.MenuItem;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class FxMenuButton extends Application {
    
    //------------------------------------------------------------
    // Menu Button
    //------------------------------------------------------------
    MenuButton menuButton;
    
    public FxMenuButton(String title, String iconFile) {
        menuButton = new MenuButton(title, new ImageView(new Image(getClass().getResourceAsStream(iconFile))));
    }
    
    public FxMenuButton(String title) {
        menuButton = new MenuButton(title);
    }
    
    public FxMenuButton() {
    }
    
    public MenuButton get() {
        return menuButton;
    }
    
    public MenuItem add(String title, String iconFile, Runnable runnable) {
        MenuItem item = new MenuItem( title);
        if( iconFile != null ) {
            item.setGraphic(new ImageView(new Image(getClass().getResourceAsStream(iconFile))));
        }
        item.setOnAction(new EventHandler<ActionEvent>() {
            public void handle(ActionEvent t) {
                runnable.run();
            }
        });
        menuButton.getItems().add(item);
        return item;
    }

    //------------------------------------------------------------
    // Example
    //------------------------------------------------------------
    @Override
    public void start(Stage stage) throws Exception {
        stage.setTitle("Menu Button Example");
        stage.getIcons().add(new Image(getClass().getResourceAsStream("/res/Window32.png")));
           
        FxMenuButton menu = new FxMenuButton("Options", "/res/Setting32.png");
        menu.add("Exit", "/res/Exit32.png", new Runnable() {@Override public void run() { System.exit(0); }    });
        menu.add("Save", "/res/Save32.png", new Runnable() {@Override public void run() { }    });
        menu.add("About", "/res/About32.png", new Runnable() {@Override public void run() { } });

        HBox hbox = new HBox(menu.get());
        Scene scene = new Scene(hbox, 320, 240);
        stage.setScene(scene);
        stage.setOnCloseRequest( e -> System.exit(0) );
        stage.show();
    }    
    
    public static void main(String[] args) {
        Application.launch(args);
    }
}


2018년 9월 9일 일요일

[JavaFx] TextArea Example


1. TextArea Example
1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import javafx.scene.Node;
import javafx.scene.control.TextArea;
import javafx.scene.input.Clipboard;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;

public class FxTextArea implements FxNode {

    FxVBox vbox;
    FxToolBar hbox;
    TextArea text;
    int textSize = 11;
    
    public FxTextArea() {
        text = new TextArea();
    }

    public FxTextArea(boolean toolbar) {
        this();
        if( toolbar ) {
            hbox = new FxToolBar();
            hbox.addToolBar();
            hbox.add(new FxButton("Clear", () -> clear() ));
            hbox.add(new FxButton("Copy", () -> copyAllText() ));
            hbox.add(new FxButton("Paste", () -> pasteAllText() ));
            hbox.add(new FxButton("Paste Html", () -> pasteAllHtml() ));
            hbox.addSeparator();
            hbox.add(new FxButton("Wrap", () -> wrapToggle() ));
            hbox.add(new FxButton("Font(-)", () -> decreaseTextSize() ));
            hbox.add(new FxButton("Font(+)", () -> increaseTextSize() ));
            VBox.setVgrow(hbox.get(), Priority.NEVER);
            VBox.setVgrow(text, Priority.ALWAYS);
            vbox = new FxVBox();
            vbox.add(hbox.get());
            vbox.add(text);
        }
    }
    
    @Override
    public Node get() {
        if( vbox != null ) {
            return vbox.get();
        } else {
            return text;
        }
    }
    
    public void setFontSize(int size) {
        if( size > 0 ) {
            textSize = size;
            text.setStyle("-fx-font-size: " + size + ";"); //1em = 50px
        }
    }
        
    
    public void increaseTextSize() {
        textSize++;
        setFontSize(textSize);
    }
    
    public void decreaseTextSize() {
        if( textSize > 1 ) {
            textSize--;
            setFontSize(textSize);
        }
    }
    
    public String getText() {
        return text.getText();
    }
    
    public void setText(String s) {
        text.setText(s);
    }
    
    public void appendText(String s) {
        text.appendText(s);
    }
    
    public void clear() {
        text.clear();
    }
    
    public void copy() {
        text.copy();
    }
    
    public void paste() {
        text.paste();
    }
    
    public void clearAllText() {
        text.clear();
    }
    
    public void copyAllText() {
        text.selectAll();
        text.copy();
        text.deselect();
    }
    
    public void pasteAllText() {
        text.clear();
        text.paste();
    }
    
    public void pasteAllHtml() {
        final Clipboard clipboard = Clipboard.getSystemClipboard();
        String data;
        if( clipboard.hasHtml() ) {
            data = clipboard.getHtml();
        } else {
            data = clipboard.getString();
        }
        text.setText(data);          
    }
    
    public void insert(int index, String data) {
        text.insertText(index, data);
    }
    
    public void append(String data) {
        text.appendText(data);
    }
    
    public void wrapToggle() {
        text.setWrapText( ! text.isWrapText() );
    }
}




[JavaFx] TableView Example


1. FxTable.java
1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
package lib.fxapp;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.event.EventHandler;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;

public class FxTable {

    public class FxTableRow {
        public StringProperty[] values;
        public FxTableRow(int columns) {
            values = new StringProperty[columns];
        }
        public void setValue(int index, String value) {
            if( index < values.length ) {
                values[index].set(value);
            }
        }
        public String getValue(int index) {
            if( index < values.length ) {
                return values[index].get();
            }
            return null;
        }
    }

    public TableView<FxTableRow> table = new TableView<>();
    public int columnCount;

   /*------------------------------------------------------------
     * Common Part
     */

    public FxTable() {     
        table = new TableView<>();
        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
        columnCount = 0;
        tableSetItemHandler(null);
        tableSetIndexHandler(null);
        setDragAndDropHandler(null);
    }
    
    public TableView<FxTableRow> getTable() {
        return table;
    }

    public void clear() {
        table.getItems().clear();
    }
    
    public int size() {
        return table.getItems().size();
    }

    public void refresh() {
        table.refresh();
    }
    
    public void clearSelection() {
        table.getSelectionModel().clearSelection();
    }
    
    public void selectFirst() {
        table.getSelectionModel().selectFirst();
    }
    
    public void selectLast() {
        table.getSelectionModel().selectLast();
    }
    
    public void enableMultiSelection() {
        table.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
    }
    
    public int getSelectedIndex() {
        return table.getSelectionModel().getSelectedIndex();
    }
    
    public ObservableList<TablePosition> getSelectedCells() {
        return table.getSelectionModel().getSelectedCells(); //TODO
    }
        
    public String[] getSelectedItem() {
        FxTableRow item = table.getSelectionModel().getSelectedItem();
        String[] row = new String[item.values.length];
        for( int i = 0; i < row.length; i++ ) {
            row[i] = item.values[i].getValue();
        }
        return row;
    }

    public void add(String[] data) {
        FxTableRow row = new FxTableRow(columnCount);
        for( int i = 0; i < data.length; i++ ) {
            row.values[i] = new SimpleStringProperty(data[i]);
        }
        table.getItems().add(row);
    }

    public String get( int row, int col ) {
        if( row < table.getItems().size() ) {
            FxTableRow item = table.getItems().get(row);
            if( col < item.values.length ) {
                return item.getValue(col);
            }
        }
        return null;
    }

    public void set(int row, int col, String data) {
        if( row >= 0 && row < table.getItems().size() ) {
            table.getItems().get(row).values[col] = new SimpleStringProperty(data);
            table.refresh();
        }
    }
    
    public void columnAlign(TableColumn<FxTableRow,?> column, int pos) {
        switch(pos) {
            case -1: column.setStyle( "-fx-alignment: CENTER-LEFT;"); break;
            case  0: column.setStyle( "-fx-alignment: CENTER;"); break;
            case  1: column.setStyle( "-fx-alignment: CENTER-RIGHT;"); break;
        }
    }
        
    public void columnAlign(int col, int pos) {
        if( pos < table.getColumns().size() ) {
            columnAlign(table.getColumns().get(col), pos);
        }
    }

    /*------------------------------------------------------------
     * Custom Part
     */    
    public void addColumn(String title, int align) {
        int columnNumber = columnCount;
        TableColumn<FxTableRow,String> column = new TableColumn<>(title);
        column.setCellValueFactory(cellData -> cellData.getValue().values[columnNumber] );
        column.setSortable(true);
        columnAlign(column,align);
        table.getColumns().add(column);
        columnCount++;
    }
    
    public void addColumn(String title) {
        addColumn(title, 0);
    }

    public void addColumns(String[] titles) {
        for( int i = 0; i < titles.length; i++ ) {
            addColumn( titles[i] );
        }
    }

    public void setColumnAlign(Integer[] align) {
        for( int i = 0; i < align.length; i++ ) {
            columnAlign( i, align[i] );
        }
    }
    
    public void setColumnWidthPercent(Integer[] widths) {
        table.setColumnResizePolicy( TableView.CONSTRAINED_RESIZE_POLICY );
        for( int i = 0; i < widths.length; i++ ) {
            TableColumn<FxTableRow,?> column = table.getColumns().get(i);
            column.setMaxWidth( 1f * Integer.MAX_VALUE * widths[i] );
        }
    }
    
    public void setColumnWidthFixed(Integer[] widths) {
        table.setColumnResizePolicy( TableView.UNCONSTRAINED_RESIZE_POLICY );
        for( int i = 0; i < widths.length; i++ ) {
            TableColumn<FxTableRow,?> column = table.getColumns().get(i);
            column.setPrefWidth( widths[i] );
        }
    }
    
    public void addCell(String[] data) {
        add(data);
    }

    public void setCellValue(int row, int col, String data) {
        set( row, col, data);
    }

    public void setSelectedCellValue(int col, String data) {
        setCellValue(table.getSelectionModel().getSelectedIndex(), col, data);
    }

    public void tableSetItemHandler(FxRunnable runnable) {
        table.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<FxTableRow>() {
            @Override
            public void changed(ObservableValue<? extends FxTableRow> observable, FxTableRow oldValue, FxTableRow newValue) {
                if( runnable != null ) {
                    runnable.run( (Object) new FxTableRow[] { oldValue, newValue } );
                }
            }
        });  
    }
    
    public void tableSetContextMenu(ContextMenu menu) {
        table.setContextMenu(menu);
    }
    
    public void tableSetIndexHandler(FxRunnable runnable) {
        table.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
            @Override
            public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                if( runnable != null ) {
                    runnable.run( (Object) new Number[] { oldValue, newValue } );
                }
            }
        });  
    }
    
    public void setDragAndDropHandler(FxRunnable runnable) {
        table.setOnDragDropped(new EventHandler<DragEvent>() {
            @Override
            public void handle(DragEvent event) {
                Dragboard db = event.getDragboard();
                boolean success = false;
                if( db.hasFiles() ) {
                    if( runnable != null ) {                 
                        runnable.run(db.getFiles());
                        success = true;
                    }
                }
                event.setDropCompleted(success);
                event.consume();
            }
        });
        
        table.setOnDragOver(new EventHandler<DragEvent>() {
            @Override
            public void handle(DragEvent event) {
                Dragboard db = event.getDragboard();
                if( db.hasFiles() ) {
                    event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
                }
                event.consume();
            }
        });
    }

    void println(String s) {
        System.out.println(s);;
    }

}


2. FxRunnable.java
1
2
3
4
5
package lib.fxapp;

public interface FxRunnable {
    public void run(Object... object);
}