[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。
|
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 | package application; import java.awt.image.BufferedImage; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import javax.imageio.ImageIO; import javax.imageio.ImageReader; import javax.imageio.stream.FileImageInputStream; import com.luciad.imageio.webp.WebPReadParam; import javafx.application.Application; import javafx.embed.swing.SwingFXUtils; import javafx.scene.Scene; import javafx.scene.image.ImageView; import javafx.scene.image.WritableImage; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; /** * * sejda-pdf/webp-imageio * * GitHub * * Maven Repository * * @author Da@ * */ public class Main extends Application { @Override public void start(Stage primaryStage) { // Scene Graphクラス AnchorPane root = new AnchorPane(); // WEBP画像読込 WritableImage img = null ; try { // 前準備 ImageReader reader = ImageIO.getImageReadersByMIMEType( "image/webp" ).next(); WebPReadParam readParam = new WebPReadParam(); readParam.setBypassFiltering( true ); // ファイルを開く reader.setInput( new FileImageInputStream( new File( "img/1.webp" ) ) ); BufferedImage bimg = reader.read( 0 , readParam ); // awtからjavaFXへ変換 img = SwingFXUtils.toFXImage( bimg , null ); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 画像をウィンドウに追加 ImageView view = new ImageView( img ); root.getChildren().add( view ); // Sceneクラス Scene scene = new Scene(root); // Stageクラス primaryStage.setScene(scene); primaryStage.show(); } public static void main( String [] args) { launch(args); } } |
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 | import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.FileImageOutputStream; import com.luciad.imageio.webp.WebPWriteParam; public class Main { public static void main( String [] args) { try { // 画像の読み込み BufferedImage image = ImageIO.read( new File( "img/b50_r.gif" )); // WebP画像出力 ImageWriter writer = ImageIO.getImageWritersByMIMEType( "image/webp" ).next(); // 出力設定 WebPWriteParam writeParam = new WebPWriteParam(writer.getLocale()); writeParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); writeParam.setCompressionType( "Lossless" ); writer.setOutput( new FileImageOutputStream( new File( "img/out.webp" ))); // WebP画像出力 writer.write( null , new IIOImage(image, null , null ), writeParam); } catch (IOException e) { e.printStackTrace(); } } } |
|
Java9以降様々なトピックがあった模様のOracle製のJava。Java9以降は商用利用が有償化していたので少し敬遠していたが、なんとJava17以降は再度無償化する(*1)(*2)とのこと。今回は、Java17+JavaFXの環境構築をやってみることにする。
1 | --module-path "(ダウンロードしたJavaFXのlibフォルダへのフルパス)" --add-modules javafx.controls,javafx.fxml |
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 | package application; import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.layout.BorderPane; public class Main extends Application { @Override public void start(Stage primaryStage) { try { BorderPane root = new BorderPane(); Scene scene = new Scene(root, 400 , 400 ); scene.getStylesheets().add(getClass().getResource( "application.css" ).toExternalForm()); primaryStage.setScene(scene); primaryStage.show(); } catch (Exception e) { e.printStackTrace(); } } public static void main( String [] args) { launch(args); } } |
|
拡張子 | 内容 |
*.shp | 図形情報 |
*.dbf | 属性情報(地名や国名、ランドマーク名など) |
*.shx | 図形(shp)に対する属性(dbf)の対応関係 |
*.prf | 投影規格(メルカトル図法など) |
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 | package application; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import org.geotools.data.FileDataStore; import org.geotools.data.FileDataStoreFinder; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.data.simple.SimpleFeatureSource; import org.geotools.geometry.jts.JTSFactoryFinder; import org.opengis.feature.simple.SimpleFeature; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.MultiPolygon; import com.vividsolutions.jts.geom.Point; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.scene.transform.Scale; import javafx.scene.transform.Translate; import javafx.stage.Stage; /** * SHPファイル表示プログラム * 「https://github.com/rafalrusin/geotools-fx-test/blob/master/src/geotools/fx/test/GeotoolsFxTest.java」 * で公開されているファイルについて、JavaFX 8 で動作するように修正 * @author karura * */ public class TestGeoMap1 extends Application { public static void main( String [] args) { launch( args); } @Override public void start(Stage primaryStage) throws Exception { Group root = new Group(); Scene scene; // シーンを作成 primaryStage.setTitle( "世界の主要都市" ); scene = new Scene(root, 1100 , 500 , Color.LIGHTBLUE); // 地図を作成 Group map = createMap( "shape/ne_50m_admin_0_countries.shp" ); Group marks = createMarks( "resource/city-country-lat-long.txt" ); map.getChildren().add( marks ); root.getChildren().addAll( map ); // 初期表示位置とズーム map.translateXProperty().set( 520 ); map.translateYProperty().set( 300 ); map.scaleXProperty().set( 3 ); map.scaleYProperty().set( -3 ); // ウィンドウ表示 primaryStage.setScene(scene); primaryStage.show(); } /** * 地図を表示するノードを作成する * @param shpFilePath * @return * @throws IOException */ protected Group createMap( String shpFilePath ) throws IOException { // 変数定義 Group map = new Group(); // 戻り値 Group mapShape = new Group(); // 地図の図形データ // SHPファイルを読込 File file = new File( shpFilePath ); FileDataStore store = FileDataStoreFinder.getDataStore(file); // ファイルからfeature(地図オブジェクト)を取得 SimpleFeatureSource featureSource = store.getFeatureSource(); SimpleFeatureCollection c = featureSource.getFeatures(); SimpleFeatureIterator featuresIterator = c.features(); // 各featureを画面出力可能なクラスに変更 while ( featuresIterator.hasNext() ) { // 1つのfeatureの取得 SimpleFeature o = featuresIterator.next(); Object geometry = o.getDefaultGeometry(); // featureが表すポリゴンを取得 // 地理情報が複合ポリゴンの場合のみ処理実行。処理対象のポリゴンを取得 if ( !( geometry instanceof MultiPolygon ) ){ continue ; } MultiPolygon multiPolygon = (MultiPolygon) geometry; // ポリゴンを画面出力可能なクラスに変換 for ( int geometryI= 0 ; geometryI<multiPolygon.getNumGeometries() ; geometryI++ ) { // 変数の初期化 Geometry polygon = multiPolygon.getGeometryN(geometryI); // ポリゴンの1つを取得 Coordinate[] coords = polygon.getCoordinates(); // ポリゴンの頂点配列を取得 // 頂点をつないでポリゴンを描く Path path = new Path(); path.setStrokeWidth( 0.05 ); path.setFill( Color.WHITE ); path.getElements().add( new MoveTo(coords[ 0 ].x, coords[ 0 ].y) ); for (Coordinate p : coords){ path.getElements().add( new LineTo( p.x, p.y ) ); } path.getElements().add( new LineTo(coords[ 0 ].x, coords[ 0 ].y) ); // マップに追加 mapShape.getChildren().add(path); } } // 画面に地図を追加 map.getChildren().add( mapShape ); // 地形 // 地図を返す return map; } /** * マークを付ける緯度経度をファイルから取り込み、表示用ノードにマーカーを置く * @param filePath * @return */ protected Group createMarks( String filePath ) { // ルートノードを作成 Group root = new Group(); // ファイルを読込(try-with-resources構文利用) try ( FileInputStream fr = new FileInputStream( filePath ); InputStreamReader ir = new InputStreamReader( fr , "UTF-8" ); BufferedReader br = new BufferedReader( ir ) ) { // 1行ずつ読み込み処理 String line = null ; while ( ( line = br.readLine() ) != null ) { // ファイルフォーマットの解析 // タブで区切って緯度経度情報を取得 String [] elements = line.split( "\t" ); String city = elements[ 0 ]; String country = elements[ 1 ]; double latitude = Double .parseDouble( elements[ 2 ] ); double longitude = Double .parseDouble( elements[ 3 ] ); // 自分で緯度・経度を画面上の点に座標変換 GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); Point point = geometryFactory.createPoint( new Coordinate( longitude , latitude )); // 点をプロット Circle c = new Circle(); c.setCenterX( point.getX() ); c.setCenterY( point.getY() ); c.setRadius( 1.0 ); c.setFill( Color.RED ); root.getChildren().add( c ); // 文字 Text t = new Text( city ); t.getTransforms().add( new Translate( point.getX() + 1.0 , point.getY() )); t.getTransforms().add( new Scale( 1.0 , -1.0 )); t.setFont( new Font( 3.0 ) ); root.getChildren().add( t ); // 点にマウスオーバーで文字を大きく c.addEventHandler( MouseEvent.MOUSE_ENTERED , e -> t.setFont( new Font( 6.0 ) ) ); c.addEventHandler( MouseEvent.MOUSE_EXITED , e -> t.setFont( new Font( 3.0 ) ) ); } } catch (Exception e) { e.printStackTrace(); } return root; } } |
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 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | package application; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.geotools.data.FileDataStore; import org.geotools.data.FileDataStoreFinder; import org.geotools.data.simple.SimpleFeatureCollection; import org.geotools.data.simple.SimpleFeatureIterator; import org.geotools.data.simple.SimpleFeatureSource; import org.opengis.feature.simple.SimpleFeature; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.MultiPolygon; import com.vividsolutions.jts.geom.Point; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.geometry.Bounds; import javafx.scene.Cursor; import javafx.scene.Group; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ProgressIndicator; import javafx.scene.input.MouseEvent; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.scene.text.Text; import javafx.scene.transform.Scale; import javafx.scene.transform.Translate; import javafx.stage.Stage; /** * SHPファイル表示プログラム * 2015年度の日本の主要輸出先への輸出額をプロット * 「https://github.com/rafalrusin/geotools-fx-test/blob/master/src/geotools/fx/test/GeotoolsFxTest.java」をベースにしている * @author karura * */ public class TestGeoMap2 extends Application { // 定数宣言(輸出国情報) private final Color[] COLORS = new Color[] { Color.RED, Color.ORANGE, Color.ORANGE, Color.ORANGE, Color.ORANGE, Color.ORANGE, Color.ORANGE, Color.ORANGE, Color.ORANGE, Color.ORANGE, Color.ORANGE }; private final String [] COUNTRIES = { "Japan" , "United States of America" , "China" , "South Korea" , "Taiwan" , "Hong Kong S.A.R." , "Thailand" , "Singapore" , "Germany" , "Australia" , "Vietnam" }; private final long[] EXPORT_VALUES = { 0 , 152246 , 132234 , 53266 , 44725 , 42360 , 33863 , 24026 , 19648 , 15549 , 15164 }; // 変数宣言(マウスドラッグ用の変数) private double dragBaseX, dragBaseY; private double dragBase2X, dragBase2Y; public static void main( String [] args) { launch( args); } @Override public void start(Stage primaryStage) throws Exception { Group root = new Group(); Scene scene; // シーンを作成 primaryStage.setTitle( "日本貿易統計:2015年度輸出額上位10ヵ国" ); scene = new Scene(root, 1100 , 500 , Color.LIGHTBLUE); // 地図を作成 Group map = createMap( "shape/ne_50m_admin_0_countries.shp" ); root.getChildren().add(map); // マウスドラッグ時の操作を定義 scene.addEventHandler( MouseEvent.MOUSE_PRESSED , e -> { // マウス押下時 scene.setCursor(Cursor.MOVE); dragBaseX = map.translateXProperty().get(); dragBaseY = map.translateYProperty().get(); dragBase2X = e.getSceneX(); dragBase2Y = e.getSceneY(); }); scene.addEventHandler( MouseEvent.MOUSE_DRAGGED , event -> { // マウスドラッグ map.setTranslateX(dragBaseX + (event.getSceneX()-dragBase2X)); map.setTranslateY(dragBaseY + (event.getSceneY()-dragBase2Y)); }); scene.addEventHandler( MouseEvent.MOUSE_RELEASED , event -> { // マウスを放したとき scene.setCursor(Cursor.DEFAULT); }); // 操作用ボタンを追加 VBox vbox = new VBox(); Button plus = new Button( "+" ); Button minus = new Button( "-" ); vbox.getChildren().add(plus); vbox.getChildren().add(minus); root.getChildren().add(vbox); plus.addEventHandler( ActionEvent.ACTION , event -> { double zoom = 1.4 ; map.scaleXProperty().set( map.scaleXProperty().get() * zoom ); map.scaleYProperty().set( map.scaleYProperty().get() * zoom ); }); minus.addEventHandler( ActionEvent.ACTION , event -> { double zoom = 1.0 / 1.4 ; map.scaleXProperty().set( map.scaleXProperty().get() * zoom ); map.scaleYProperty().set( map.scaleYProperty().get() * zoom ); }); // ウィンドウ表示 primaryStage.setScene(scene); primaryStage.show(); } /** * 地図を表示するノードを作成する * @param shpFilePath * @return * @throws IOException */ protected Group createMap( String shpFilePath ) throws IOException { // 変数定義 Group map = new Group(); // 戻り値 Group mapShape = new Group(); // 地図の図形データ Group textNotExport = new Group(); // 輸出国以外の国名 Group textExport = new Group(); // 輸出国名 Group lineExport = new Group(); // 輸出国間に引く線 // SHPファイルを読込 File file = new File( shpFilePath ); FileDataStore store = FileDataStoreFinder.getDataStore(file); // ファイルからfeature(地図オブジェクト)を取得 SimpleFeatureSource featureSource = store.getFeatureSource(); SimpleFeatureCollection c = featureSource.getFeatures(); SimpleFeatureIterator featuresIterator = c.features(); // 各featureを画面出力可能なクラスに変更 Map< String ,Point> countryMap = new HashMap< String ,Point>(); while ( featuresIterator.hasNext() ) { // 1つのfeatureの取得 SimpleFeature o = featuresIterator.next(); int countryIndex = 0 ; // 処理対象が表す国番号 String name = ( String ) o.getAttribute( "sovereignt" ); // featureが表す国名を取得 String type = ( String ) o.getAttribute( "type" ); // featureが示すタイプ(国(country)や属国(dependency)など) String subUnit = ( String ) o.getAttribute( "subunit" ); // featureが示すサブユニット(地域名) Object geometry = o.getDefaultGeometry(); // featureが表すポリゴンを取得 // 地理情報が複合ポリゴンの場合のみ処理実行。処理対象のポリゴンを取得 if ( !( geometry instanceof MultiPolygon ) ){ continue ; } MultiPolygon multiPolygon = (MultiPolygon) geometry; // ポリゴンを画面出力可能なクラスに変換 for ( int geometryI= 0 ; geometryI<multiPolygon.getNumGeometries() ; geometryI++ ) { // 変数の初期化 Geometry polygon = multiPolygon.getGeometryN(geometryI); // ポリゴンの1つを取得 Coordinate[] coords = polygon.getCoordinates(); // ポリゴンの頂点配列を取得 // 地形の塗りつぶし色を定義 java.util.List< String > countries = Arrays.asList( COUNTRIES ); Color currentColor = null ; if ( countries.contains( name ) ) { // 輸出国リストにある場合、国番号と色を取得 countryIndex = countries.indexOf( name ); currentColor = COLORS[ countryIndex ]; } else { // 輸出国リストにない場合、デフォルトの国番号と色を取得 countryIndex = 0 ; currentColor = Color.ALICEBLUE; } // 頂点をつないでポリゴンを描く Path path = new Path(); path.setStrokeWidth( 0.05 ); path.setFill(currentColor); path.getElements().add( new MoveTo(coords[ 0 ].x, coords[ 0 ].y) ); for (Coordinate p : coords){ path.getElements().add( new LineTo( p.x, p.y ) ); } path.getElements().add( new LineTo(coords[ 0 ].x, coords[ 0 ].y) ); // マップに追加 mapShape.getChildren().add(path); } // 本国以外はテキストを表示しない // 国を表すfeatureでない場合は、テキスト情報を出力しない。 // 本国名とサブユニット名が異なる場合はテキスト情報を出力しない。(香港だけ特別扱い) if ( type.equalsIgnoreCase( "dependency" ) ){ continue ; } if ( ! ( subUnit.equals( name ) || subUnit.equals( "Hong Kong S.A.R." ) ) ){ continue ; } // 国名と輸出額表示ノードを作成 Node node = ( countryIndex == 0 )? new Text( subUnit ) : createExportValue( subUnit , EXPORT_VALUES[ countryIndex ] ); // 国名と輸出額表示ノードの位置を設定 Point centroid = multiPolygon.getCentroid(); // ポリゴンの重心座標を取得 Bounds bounds = node.getBoundsInLocal(); node.getTransforms().add( new Translate(centroid.getX(), centroid.getY())); node.getTransforms().add( new Scale( 0.1 , -0.1 )); node.getTransforms().add( new Translate(-bounds.getWidth()/ 2. , bounds.getHeight()/ 2. )); // シーングラフに追加 Group group = ( countryIndex == 0 )? textNotExport : textExport; group.getChildren().add( node ); // 後で矢印を描くために各国の重心位置を保持 countryMap.put( subUnit , centroid ); } // 矢印を描く for ( int i= 1 ; i<COUNTRIES.length ; i++ ) { // 位置を取得 Point pFrom = countryMap.get( COUNTRIES[ 0 ] ); Point pTo = countryMap.get( COUNTRIES[i] ); if ( ( pFrom == null ) || ( pTo == null ) ){ continue ; } // 矢印を記入 Path path = new Path(); path.setStrokeWidth( 0.25 ); path.setStroke( Color.BLACK ); path.setOpacity( 0.5 ); path.getElements().add( new MoveTo( pFrom.getX() , pFrom.getY() ) ); path.getElements().add( new LineTo( pTo.getX() , pTo.getY() ) ); lineExport.getChildren().add( path ); } // 画面に地図と文字を追加 map.getChildren().add( mapShape ); // 地形 map.getChildren().add( textNotExport ); // 輸出国以外の国名 map.getChildren().add( lineExport ); // 輸出国間の線 map.getChildren().add( textExport ); // 輸出国名 // 初期表示位置とズーム map.translateXProperty().set( 520 ); map.translateYProperty().set( 300 ); map.scaleXProperty().set( 3 ); map.scaleYProperty().set( -3 ); // 地図を返す return map; } /** * 輸出額を示すテキスト情報を表示するノードを作成 * @param name 国名 * @param exportValue 輸出額 * @return */ protected Node createExportValue( String name , long exportValue ) { // ルートノード VBox root = new VBox(); // グラフを追加 ProgressIndicator pi = new ProgressIndicator(); long sum = 0 ; for ( long value : EXPORT_VALUES ){ sum += value; } pi.setProgress( (double) exportValue / sum ); pi.setPrefSize( 50 , 50 ); root.getChildren().add( pi ); // テキストを追加 Text country = new Text( name ); Text value = new Text( String .format( "( %,3d億円 )" ,exportValue ) ); country.setFill( Color.RED ); value.setFill( Color.RED ); root.getChildren().addAll( country , value ); return root; } } |
|
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 | package application; import java.io.File; import javafx.application.Application; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.print.PrinterJob; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class TestPrint1 extends Application { public static void main( String [] args) { launch(args); } @Override public void start(Stage primaryStage) { // フォント色がおかしくなることへの対処 System.setProperty( "prism.lcdtext" , "false" ); // シーングラフの作成 VBox root = new VBox(); Label label = new Label( "印刷テスト" ); Image img = new Image( new File( "img/ean13.png" ).toURI().toString() ); ImageView view = new ImageView( img ); Button button = new Button( "印刷" ); root.getChildren().addAll( label , view , button ); // シーンの作成 Scene scene = new Scene( root , 250 , 200 ); // ウィンドウ表示 primaryStage.setScene( scene ); primaryStage.show(); // 印刷ボタンにイベントハンドラを設定 button.addEventFilter( ActionEvent.ACTION , e -> { // 印刷タスクを定義 Task< Boolean > printTask = new Task< Boolean >() { @Override public Boolean call() { // 印刷ジョブの作成 PrinterJob job = PrinterJob.createPrinterJob(); if ( job == null ){ return false ; } // ジョブ状態を標準出力 job.jobStatusProperty().addListener( e -> System.out.println( "status : " + e ) ); // 印刷ダイアログの表示 if ( !job.showPrintDialog(primaryStage) ){ return false ; } // ページ設定ダイアログの表示 if ( !job.showPageSetupDialog(primaryStage) ){ return false ; } // シーングラフを印刷 if ( !job.printPage( root ) ){ return false ; } // 印刷ジョブの終了 return job.endJob(); } }; // 別スレッドで印刷を開始 Thread thread = new Thread( printTask ); thread.setDaemon( true ); thread.start(); }); } } |
(出力画面) |
(ボタン押下で表示される印刷ダイアログ) |
(ボタン押下で表示されるページ設定ダイアログ) |
(印刷結果。プリンタとしてPDF出力を選択) |
階層1 | 階層2 | 階層3 |
Printer (プリンター。PrinterJob::getPrinter関数等で取得) |
PageLayout (ページレイアウト。Printer::createPageLayout関数で作成) |
Paper (用紙サイズ) |
PageOrientation (用紙向き) |
||
Printer.MarginType (マージン) |
||
JobSettings (ジョブ設定。Printer::getJobSettings関数で取得) |
Name (ジョブ名) |
|
Collation (丁合) |
||
Copies (印刷部数) |
||
PageaRange (印刷ページ指定) |
||
PaperSource (給紙方法) |
||
PrintColor (カラー設定) |
||
PrintQuality (印刷品質) |
||
PrintResolution (印刷解像度) |
||
PrintSides (両面印刷設定) |
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 | package application; import javafx.application.Application; import javafx.collections.ObservableSet; import javafx.print.Collation; import javafx.print.PageOrientation; import javafx.print.Paper; import javafx.print.PaperSource; import javafx.print.PrintColor; import javafx.print.PrintQuality; import javafx.print.PrintResolution; import javafx.print.PrintSides; import javafx.print.Printer; import javafx.print.PrinterAttributes; import javafx.stage.Stage; public class TestPrint2 extends Application { public static void main( String [] args) { launch(args); } @Override public void start(Stage primaryStage) { // プリンター一覧を出力 ObservableSet<Printer> printers = Printer.getAllPrinters(); for ( Printer printer : printers ) { // プリンタ情報を出力 String def = ( printer == Printer.getDefaultPrinter() )? "default - " : "" ; String name = printer.getName(); PrinterAttributes attr = printer.getPrinterAttributes(); // 名前 System.out.println( String .format( "%s%s" , def , name ) ); // 丁合 System.out.println( String .format( "◆利用可能な丁合:(デフォルト%s)" , attr.getDefaultCollation() ) ); for ( Collation c : attr.getSupportedCollations() ) { System.out.println( String .format( " %s" , c ) ); } // 印刷部数 System.out.println( String .format( "◆印刷部数:(デフォルト%s)" , attr.getDefaultCopies() ) ); System.out.println( String .format( " 最大印刷部数:%s" , attr.getMaxCopies() ) ); // 用紙向き System.out.println( String .format( "◆利用可能な用紙向き:(デフォルト%s)" , attr.getDefaultPageOrientation() ) ); for ( PageOrientation o : attr.getSupportedPageOrientations() ) { System.out.println( String .format( " %s" , o ) ); } // 用紙サイズ System.out.println( String .format( "◆利用可能な用紙サイズ:(デフォルト%s)" , attr.getDefaultPaper() ) ); for ( Paper p : attr.getSupportedPapers() ) { System.out.println( String .format( " %s" , p ) ); } // 給紙方法 System.out.println( String .format( "◆利用可能な給紙方法:(デフォルト%s)" , attr.getDefaultPaperSource() ) ); for ( PaperSource p : attr.getSupportedPaperSources() ) { System.out.println( String .format( " %s" , p.getName() ) ); } // 色設定 System.out.println( String .format( "◆利用可能な色設定:(デフォルト%s)" , attr.getDefaultPrintColor() ) ); for ( PrintColor p : attr.getSupportedPrintColors() ) { System.out.println( String .format( " %s" , p ) ); } // 品質設定 System.out.println( String .format( "◆利用可能な品質設定:(デフォルト%s)" , attr.getDefaultPrintQuality() ) ); for ( PrintQuality p : attr.getSupportedPrintQuality() ) { System.out.println( String .format( " %s" , p ) ); } // 印刷解像度 System.out.println( String .format( "◆利用可能な印刷解像度:(デフォルト%s)" , attr.getDefaultPrintResolution() ) ); for ( PrintResolution p : attr.getSupportedPrintResolutions() ) { System.out.println( String .format( " %s" , p ) ); } // 両面設定 System.out.println( String .format( "◆利用可能な両面印刷:(デフォルト%s)" , attr.getDefaultPrintSides() ) ); for ( PrintSides p : attr.getSupportedPrintSides() ) { System.out.println( String .format( " %s" , p ) ); } // ページ範囲サポート System.out.println( attr.supportsPageRanges() ? "ページ範囲サポートあり" : "ページ範囲サポートなし" ); System.out.println( "" ); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | default - CubePDF ◆利用可能な丁合:(デフォルトCOLLATED) UNCOLLATED COLLATED ◆印刷部数:(デフォルト1) 最大印刷部数:999 ◆利用可能な用紙向き:(デフォルトPORTRAIT) PORTRAIT LANDSCAPE REVERSE_LANDSCAPE ◆利用可能な用紙サイズ:(デフォルトPaper: A4 size=210.0x297.0 MM) Paper: 8x10 size=8.0x10.0 INCH Paper: A0 size=841.0x1189.0 MM Paper: A1 size=594.0x841.0 MM Paper: A2 size=420.0x594.0 MM Paper: A3 size=297.0x420.0 MM … |
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 | package application; import java.net.URL; import javafx.application.Application; import javafx.event.ActionEvent; import javafx.fxml.FXMLLoader; import javafx.print.PageLayout; import javafx.print.PageOrientation; import javafx.print.Paper; import javafx.print.Printer; import javafx.print.PrinterJob; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.stage.Modality; import javafx.stage.Stage; public class TestPrint3 extends Application { public static void main( String [] args) { launch(args); } @Override public void start(Stage primaryStage) { // フォント色がおかしくなることへの対処 System.setProperty( "prism.lcdtext" , "false" ); // シーングラフの作成 VBox root = new VBox(); Label label = new Label( "帳票印刷プログラム" ); TextField name = new TextField(); name.setPromptText( "出力する名前を入力してください。" ); TextField money = new TextField(); money.setPromptText( "出力する金額を入力してください。" ); Button button = new Button( "印刷" ); root.getChildren().addAll( label , name , money , button ); // シーンの作成 Scene scene = new Scene( root , 250 , 200 ); // ウィンドウ表示 primaryStage.setScene( scene ); primaryStage.show(); // 印刷ボタンにイベントハンドラを設定 button.addEventFilter( ActionEvent.ACTION , e -> { // FXMLの読込設定 URL location = getClass().getResource( "TestPrintReport.fxml" ); FXMLLoader fxmlLoader = new FXMLLoader( location ); // FXMLファイルの読込 Pane report = null ; Stage reportWin = null ; try { // FXMLの読込 report = (Pane) fxmlLoader.load(); // 値の設定 TestPrint3ReportController controller; controller = fxmlLoader.getController(); controller.setName( name.getText() ); controller.setMoney( money.getText() ); // ウィンドウの表示 Scene reportScene = new Scene( report , report.getPrefWidth() , report.getPrefHeight() ); reportWin = new Stage(); reportWin.initModality( Modality.APPLICATION_MODAL ); reportWin.initOwner( primaryStage ); reportWin.setScene( reportScene ); reportWin.setWidth( report.getWidth() ); reportWin.setHeight( report.getHeight() ); reportWin.setTitle( "now printing..." ); reportWin.show(); } catch ( Exception e1 ){ e1.printStackTrace(); } // 印刷ジョブの作成 PrinterJob job = PrinterJob.createPrinterJob(); if ( job == null ){ return ; } // ジョブ状態を標準出力 job.jobStatusProperty().addListener( status -> System.out.println( "status : " + status ) ); // ジョブ名を設定 job.getJobSettings().setJobName( "領収書" ); // デフォルトプリンター(サイズ:A4横)でシーングラフを印刷 Printer printer = Printer.getDefaultPrinter(); PageLayout layout = printer.createPageLayout( Paper.A4 , PageOrientation.LANDSCAPE , Printer.MarginType.DEFAULT ); if ( !job.printPage( layout , report ) ){ return ; } // 印刷ジョブの終了 if ( !job.endJob() ){ return ; } // ウィンドウを閉じる reportWin.close(); }); } } |
(画面) |
(印刷ボタン押下時に表示される画面) |
(PDFに出力された内容。以下は、右回りに90度回転させた状態) |
|
ライブラリ名 | 必要ファイル | ダウンロード場所 |
ROME 1.7 | rome-1.7.0-SNAPSHOT.jar | ・Github 「rometools/rome」 →最新ソース。コンパイルにはMavenが必要。 ・MVN Repository →コンパイル済Jar。ただしver1.6 |
ROME-utils 1.6 | rome-utils-1.7.0-SNAPSHOT.jar | ・MVN Repository →ページ下部のリンク |
JDOM 2.0.6 | jdom2-2.0.6.jar | ・MVN Repository →ページ下部のリンク |
SLF4J 1.7.21 | slf4j-api-1.7.21.jar slf4j-simple-1.7.21.jar |
・MVN Repository →ページ下部のリンク |
Apache HTTPClient(*) | commons-codec-1.9.jar commons-logging-1.2.jar httpclient-4.5.2.jar httpclient-cache-4.5.2.jar httpclient-win-4.5.2.jar httpcore-4.4.4.jar httpmime-4.5.2.jar |
・Apache Software「HttpComponents Downloads」 →最新版のzipファイルを解凍し、左記のファイルを取得 |
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 | package application; import java.awt.Desktop; import java.io.InputStream; import java.net.URI; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import com.rometools.rome.feed.synd.SyndEntryImpl; import com.rometools.rome.feed.synd.SyndFeed; import com.rometools.rome.io.SyndFeedInput; import com.rometools.rome.io.XmlReader; import javafx.application.Application; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.scene.Node; import javafx.scene.Scene; import javafx.scene.control.Hyperlink; import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane.ScrollBarPolicy; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.VBox; import javafx.stage.Stage; public class TestRomeRead extends Application { // 定数 protected static final int WIDTH = 300 ; protected static final int HEIGHT = 500 ; public static void main( String [] args) { launch(args); } @Override public void start(Stage primaryStage) throws Exception { // フォント色がおかしくなることへの対処 System.setProperty( "prism.lcdtext" , "false" ); // シーングラフの作成 ScrollPane scroll = new ScrollPane(); VBox root = new VBox(); scroll.setContent( root ); scroll.setHbarPolicy( ScrollBarPolicy.NEVER ); scroll.setVbarPolicy( ScrollBarPolicy.ALWAYS ); // シーンの作成 Scene scene = new Scene( scroll , WIDTH , HEIGHT ); // ウィンドウ表示 primaryStage.setScene( scene ); primaryStage.show(); // RSSの取込・表示を遅延実行タスクを定義 Task< Boolean > task = new Task< Boolean >() { @Override public Boolean call() throws Exception { // RSSのURLを指定 SyndFeed feed = null ; // RSSフィードを読み込み(キャッシュ機能付き)。 // try-with-resources構文での記述 try ( CloseableHttpClient client = HttpClients.createMinimal() ) { // HTTPリクエストの作成 HttpUriRequest method = new HttpGet(uri); // HTTPリクエストを発行 try ( CloseableHttpResponse response = client.execute(method); InputStream stream = response.getEntity().getContent() ) { // フィードを読込 SyndFeedInput input = new SyndFeedInput(); feed = input.build( new XmlReader(stream)); } } // 画面表示 for ( Object entry : feed.getEntries() ) { // エントリーの取得 SyndEntryImpl e = (SyndEntryImpl) entry; // エントリーを順次表示 Node node = createDrawrEntry( e ); Platform.runLater( () -> root.getChildren().add( node ) ); } return null ; } }; // RSS取込・表示の遅延実行開始 Thread t = new Thread( task ); t.setDaemon( true ); t.start(); } /** * DrawrのRSSフィードから表示用のノードを作成する * @param e * @return */ protected Node createDrawrEntry( SyndEntryImpl e ) { // エントリーの取得 String author = e.getAuthor(); String title = e.getTitle(); String link = e.getLink(); String value = e.getDescription().getValue(); // 画像URL解析 String imgUrl = value.substring( value.indexOf( "http" ) , value.lastIndexOf( "\"" ) ); // 画目出力 Image img = new Image( imgUrl ); ImageView view = new ImageView( img ); Hyperlink hyperLink = new Hyperlink(); hyperLink.setText( title + "(" + author + ")" ); hyperLink.setGraphic( view ); hyperLink.setOnAction( arg -> { try { // デフォルト・ブラウザを起動 Desktop desktop = Desktop.getDesktop(); desktop.browse( new URI( link ) ); } catch (Exception e1) { e1.printStackTrace(); } }); // 表示ノードを返す return hyperLink; } } |
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 | package application; import java.io.File; import java.sql.Date; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import com.sun.syndication.feed.synd.SyndContent; import com.sun.syndication.feed.synd.SyndContentImpl; import com.sun.syndication.feed.synd.SyndEntry; import com.sun.syndication.feed.synd.SyndEntryImpl; import com.sun.syndication.feed.synd.SyndFeed; import com.sun.syndication.feed.synd.SyndFeedImpl; import com.sun.syndication.io.SyndFeedOutput; public class TestRomeCreate { // 定数 protected static final int WIDTH = 300 ; protected static final int HEIGHT = 500 ; protected static final String [] RSS_TYPE = { "rss_1.0" , "rss_2.0" , "rss_0.9" , "rss_0.92" , "atom_1.0" , "atom_0.3" }; public static void main( String [] args) throws Exception { // 変数 final String filename = "rss.xml" ; // 出力先RSS // フィードの全体情報を設定 SyndFeed feed = new SyndFeedImpl(); feed.setTitle( "RSSのタイトルです" ); feed.setDescription( "RSSの内容を表す紹介文です" ); feed.setFeedType( RSS_TYPE[ 1 ] ); // フィードの記事を作成 List<SyndEntry> entries = new ArrayList<SyndEntry>(); for ( int i= 0 ; i< 10 ; i++ ) { // 1つ分の記事を作成 SyndEntry entry = new SyndEntryImpl(); SyndContent desc = new SyndContentImpl(); entry.setDescription( desc ); entry.setTitle( String .format( "%d番目の記事のタイトル" , i ) ); entry.setPublishedDate( Date.valueOf( LocalDate.now() ) ); desc.setType( "text/plain" ); desc.setValue( String .format( "%d番目の記事の内容" , i ) ); // 一覧に記事を追加 entries.add( entry ); } // 記事一覧をフィードに追加 feed.setEntries( entries ); // RSSフィードライタを作成し、ファイル出力 SyndFeedOutput o = new SyndFeedOutput(); o.output(feed, new File( filename ) ); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <? xml version = "1.0" encoding = "UTF-8" ?> < channel > < title >RSSのタイトルです</ title > < description >RSSの内容を表す紹介文です</ description > < item > < title >0番目の記事のタイトル</ title > < description >0番目の記事の内容</ description > < pubDate >Sat, 09 Apr 2016 15:00:00 GMT</ pubDate > < dc:date >2016-04-09T15:00:00Z</ dc:date > </ item > < item > < title >1番目の記事のタイトル</ title > …中略 </ item > </ channel > </ rss > |
|
(11/14) | JavaFX 画面キャプチャ(コマ撮り) |
(11/11) | JavaFX WebP画像ファイルを開く(webp-imageioライブラリ) |
(11/07) | EclipseでJavaFX入門(Java17での環境構築) |
(06/29) | Java DeepLearning4j 単語のベクトル化(Word2Vec) |
(06/11) | Java DeepLearning4j パラメータの設定 |