tag:blogger.com,1999:blog-16615175189257620102024-03-12T21:08:44.579-07:00Java-BuddyErikhttp://www.blogger.com/profile/04983894331825656853noreply@blogger.comBlogger734125tag:blogger.com,1999:blog-1661517518925762010.post-75109477452266295442016-07-20T09:21:00.001-07:002016-07-20T09:30:11.870-07:00Java example of SSL Server and Client, and how to generate keystore Here are examples of Java SSL Server and Client.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-6iW5WhsLZTI/V4-kBWwS70I/AAAAAAAAC6k/wJrWCRQALvQ0uIs3UCUSUG8nih-dPIR_ACLcB/s1600/SSLServer%2Band%2BClient.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="330" src="https://2.bp.blogspot.com/-6iW5WhsLZTI/V4-kBWwS70I/AAAAAAAAC6k/wJrWCRQALvQ0uIs3UCUSUG8nih-dPIR_ACLcB/s640/SSLServer%2Band%2BClient.png" width="640" /></a></div>
<br />
<br />
JavaSSLServer.java
<br />
<pre class="brush: java">package javasslserver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLServerSocketFactory;
/**
* @web http://java-buddy.blogspot.com/
*/
public class JavaSSLServer {
static final int port = 8000;
public static void main(String[] args) {
SSLServerSocketFactory sslServerSocketFactory =
(SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
try {
ServerSocket sslServerSocket =
sslServerSocketFactory.createServerSocket(port);
System.out.println("SSL ServerSocket started");
System.out.println(sslServerSocket.toString());
Socket socket = sslServerSocket.accept();
System.out.println("ServerSocket accepted");
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
try (BufferedReader bufferedReader =
new BufferedReader(
new InputStreamReader(socket.getInputStream()))) {
String line;
while((line = bufferedReader.readLine()) != null){
System.out.println(line);
out.println(line);
}
}
System.out.println("Closed");
} catch (IOException ex) {
Logger.getLogger(JavaSSLServer.class.getName())
.log(Level.SEVERE, null, ex);
}
}
}
</pre>
<br />
JavaSSLClient.java
<br />
<pre class="brush: java">package javasslclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLSocketFactory;
/**
* @web http://java-buddy.blogspot.com/
*/
public class JavaSSLClient {
static final int port = 8000;
public static void main(String[] args) {
SSLSocketFactory sslSocketFactory =
(SSLSocketFactory)SSLSocketFactory.getDefault();
try {
Socket socket = sslSocketFactory.createSocket("localhost", port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
try (BufferedReader bufferedReader =
new BufferedReader(
new InputStreamReader(socket.getInputStream()))) {
Scanner scanner = new Scanner(System.in);
while(true){
System.out.println("Enter something:");
String inputLine = scanner.nextLine();
if(inputLine.equals("q")){
break;
}
out.println(inputLine);
System.out.println(bufferedReader.readLine());
}
}
} catch (IOException ex) {
Logger.getLogger(JavaSSLClient.class.getName())
.log(Level.SEVERE, null, ex);
}
}
}
</pre>
<br />
<br />
Without keystore, both the server and client will fail. This video show how to generate keystore using keytool program. Then run server and client with keystore and password.<br />
<br />
<center>
<iframe allowfullscreen="" frameborder="0" height="360" src="https://www.youtube.com/embed/X4WImgwvjDw" width="640"></iframe>
</center>
<br />
Type the following command in your command window to create a keystore named examplestore and to generate keys:<br />
<br />
<b>$ keytool -genkey -alias signFiles -keystore examplestore</b><br />
<br />
You will be prompted to enter passwords for the key and keystore. The password in this example is "password".<br />
<br />
(reference: <a href="https://docs.oracle.com/javase/tutorial/security/toolsign/step3.html" target="_blank">https://docs.oracle.com/javase/tutorial/security/toolsign/step3.html</a>)<br />
<br />
Run SSL server and client by entering the commands:<br />
<b>$ java -jar -Djavax.net.ssl.keyStore=keystore -Djavax.net.ssl.keyStorePassword=password "...JavaSSLServer.jar"</b><br />
<b>$ java -jar -Djavax.net.ssl.trustStore=keystore -Djavax.net.ssl.trustStorePassword=password "...JavaSSLClient.jar"</b><br />
<br />
<br />Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-1174347990544386732016-06-16T09:25:00.001-07:002016-06-16T09:25:24.110-07:00Read csv, run in background thread and update JavaFX TableView dynamically<center>
<iframe allowfullscreen="" frameborder="0" height="360" src="https://www.youtube.com/embed/8UVbhzuYFIw" width="640"></iframe>
</center>
<br />
It's modified version of last example "<a href="http://java-buddy.blogspot.com/2016/06/read-csv-file-display-in-javafx.html">Read csv file, display in JavaFX TableView</a>", with the job run in background thread. I also add dummy delay to simulate long time operation in background thread.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-U41QORdwH9I/V2LSrK2O_gI/AAAAAAAAC6U/UQKpBt_MkMMFnzcoITlS07w58Ok3TEc-wCLcB/s1600/JavaFXCSVTableView%2Bin%2Bbackground%2Bthread.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="330" src="https://1.bp.blogspot.com/-U41QORdwH9I/V2LSrK2O_gI/AAAAAAAAC6U/UQKpBt_MkMMFnzcoITlS07w58Ok3TEc-wCLcB/s640/JavaFXCSVTableView%2Bin%2Bbackground%2Bthread.png" width="640" /></a></div>
<br />
JavaFXCSVTableView.java
<br />
<pre class="brush: java">package javafxcsvtableview;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
* @web http://java-buddy.blogspot.com/
*/
public class JavaFXCSVTableView extends Application {
public class Record {
//Assume each record have 6 elements, all String
private SimpleStringProperty f1, f2, f3, f4, f5, f6;
public String getF1() {
return f1.get();
}
public String getF2() {
return f2.get();
}
public String getF3() {
return f3.get();
}
public String getF4() {
return f4.get();
}
public String getF5() {
return f5.get();
}
public String getF6() {
return f6.get();
}
Record(String f1, String f2, String f3, String f4,
String f5, String f6) {
this.f1 = new SimpleStringProperty(f1);
this.f2 = new SimpleStringProperty(f2);
this.f3 = new SimpleStringProperty(f3);
this.f4 = new SimpleStringProperty(f4);
this.f5 = new SimpleStringProperty(f5);
this.f6 = new SimpleStringProperty(f6);
}
}
private final TableView<Record> tableView = new TableView<>();
private final ObservableList<Record> dataList
= FXCollections.observableArrayList();
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("java-buddy.blogspot.com");
Group root = new Group();
TableColumn columnF1 = new TableColumn("f1");
columnF1.setCellValueFactory(
new PropertyValueFactory<>("f1"));
TableColumn columnF2 = new TableColumn("f2");
columnF2.setCellValueFactory(
new PropertyValueFactory<>("f2"));
TableColumn columnF3 = new TableColumn("f3");
columnF3.setCellValueFactory(
new PropertyValueFactory<>("f3"));
TableColumn columnF4 = new TableColumn("f4");
columnF4.setCellValueFactory(
new PropertyValueFactory<>("f4"));
TableColumn columnF5 = new TableColumn("f5");
columnF5.setCellValueFactory(
new PropertyValueFactory<>("f5"));
TableColumn columnF6 = new TableColumn("f6");
columnF6.setCellValueFactory(
new PropertyValueFactory<>("f6"));
tableView.setItems(dataList);
tableView.getColumns().addAll(
columnF1, columnF2, columnF3, columnF4, columnF5, columnF6);
VBox vBox = new VBox();
vBox.setSpacing(10);
vBox.getChildren().add(tableView);
root.getChildren().add(vBox);
primaryStage.setScene(new Scene(root, 700, 250));
primaryStage.show();
//readCSV();
//run in background thread
new Thread() {
@Override
public void run() {
readCSV();
};
}.start();
}
private void readCSV() {
System.out.println("Platform.isFxApplicationThread(): "
+ Platform.isFxApplicationThread());
String CsvFile = "/home/buddy/test/test.csv";
String FieldDelimiter = ",";
BufferedReader br;
try {
br = new BufferedReader(new FileReader(CsvFile));
String line;
while ((line = br.readLine()) != null) {
String[] fields = line.split(FieldDelimiter, -1);
Record record = new Record(fields[0], fields[1], fields[2],
fields[3], fields[4], fields[5]);
dataList.add(record);
//Add delay to simulate long time operation
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(JavaFXCSVTableView.class.getName())
.log(Level.SEVERE, null, ex);
}
}
} catch (FileNotFoundException ex) {
Logger.getLogger(JavaFXCSVTableView.class.getName())
.log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(JavaFXCSVTableView.class.getName())
.log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
launch(args);
}
}
</pre>
Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-31371200786754502082016-06-16T08:52:00.000-07:002016-06-16T09:26:59.349-07:00Read csv file, display in JavaFX TableViewJava example read csv file and display the content in JavaFX TableView.<br />
<br />
To know how to prepare the csv file, and simple read csv file, refer to <a href="http://java-buddy.blogspot.com/2016/06/java-to-read-csv-file.html">last post</a>.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-putxoEajeXw/V2LKwJyXWuI/AAAAAAAAC6E/pmxs2Y_IoxcalluyX1OW8r1zPaYcqvFlQCLcB/s1600/JavaFXCSVTableView.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="330" src="https://1.bp.blogspot.com/-putxoEajeXw/V2LKwJyXWuI/AAAAAAAAC6E/pmxs2Y_IoxcalluyX1OW8r1zPaYcqvFlQCLcB/s640/JavaFXCSVTableView.png" width="640" /></a></div>
<br />
JavaFXCSVTableView.java
<br />
<pre class="brush: java">package javafxcsvtableview;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
/**
* @web http://java-buddy.blogspot.com/
*/
public class JavaFXCSVTableView extends Application {
public class Record {
//Assume each record have 6 elements, all String
private SimpleStringProperty f1, f2, f3, f4, f5, f6;
public String getF1() {
return f1.get();
}
public String getF2() {
return f2.get();
}
public String getF3() {
return f3.get();
}
public String getF4() {
return f4.get();
}
public String getF5() {
return f5.get();
}
public String getF6() {
return f6.get();
}
Record(String f1, String f2, String f3, String f4,
String f5, String f6) {
this.f1 = new SimpleStringProperty(f1);
this.f2 = new SimpleStringProperty(f2);
this.f3 = new SimpleStringProperty(f3);
this.f4 = new SimpleStringProperty(f4);
this.f5 = new SimpleStringProperty(f5);
this.f6 = new SimpleStringProperty(f6);
}
}
private final TableView<Record> tableView = new TableView<>();
private final ObservableList<Record> dataList
= FXCollections.observableArrayList();
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("java-buddy.blogspot.com");
Group root = new Group();
TableColumn columnF1 = new TableColumn("f1");
columnF1.setCellValueFactory(
new PropertyValueFactory<>("f1"));
TableColumn columnF2 = new TableColumn("f2");
columnF2.setCellValueFactory(
new PropertyValueFactory<>("f2"));
TableColumn columnF3 = new TableColumn("f3");
columnF3.setCellValueFactory(
new PropertyValueFactory<>("f3"));
TableColumn columnF4 = new TableColumn("f4");
columnF4.setCellValueFactory(
new PropertyValueFactory<>("f4"));
TableColumn columnF5 = new TableColumn("f5");
columnF5.setCellValueFactory(
new PropertyValueFactory<>("f5"));
TableColumn columnF6 = new TableColumn("f6");
columnF6.setCellValueFactory(
new PropertyValueFactory<>("f6"));
tableView.setItems(dataList);
tableView.getColumns().addAll(
columnF1, columnF2, columnF3, columnF4, columnF5, columnF6);
VBox vBox = new VBox();
vBox.setSpacing(10);
vBox.getChildren().add(tableView);
root.getChildren().add(vBox);
primaryStage.setScene(new Scene(root, 700, 250));
primaryStage.show();
readCSV();
}
private void readCSV() {
String CsvFile = "/home/buddy/test/test.csv";
String FieldDelimiter = ",";
BufferedReader br;
try {
br = new BufferedReader(new FileReader(CsvFile));
String line;
while ((line = br.readLine()) != null) {
String[] fields = line.split(FieldDelimiter, -1);
Record record = new Record(fields[0], fields[1], fields[2],
fields[3], fields[4], fields[5]);
dataList.add(record);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(JavaFXCSVTableView.class.getName())
.log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(JavaFXCSVTableView.class.getName())
.log(Level.SEVERE, null, ex);
}
}
public static void main(String[] args) {
launch(args);
}
}
</pre>
<br />
<a href="http://java-buddy.blogspot.com/2016/06/read-csv-run-in-background-thread-and.html">Next post</a> show how to do the job in background.<br />
<br />Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-15024812632253160912016-06-15T10:03:00.002-07:002016-06-16T08:53:24.909-07:00Java to read csv fileThis example show how to read csv file using Java.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-INZqg7kh6Q4/V2GJJsuODaI/AAAAAAAAC5Y/g1Vgh8nYV9ojoxzjmdecogYSVpfJ-fpyQCLcB/s1600/JavaReadCSV.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="329" src="https://1.bp.blogspot.com/-INZqg7kh6Q4/V2GJJsuODaI/AAAAAAAAC5Y/g1Vgh8nYV9ojoxzjmdecogYSVpfJ-fpyQCLcB/s640/JavaReadCSV.png" width="640" /></a></div>
<br />
Prepare:<br />
- Create a spreadsheet:<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-ImNhZVsDOTE/V2GJYhXk1EI/AAAAAAAAC5g/_43JcdzUgLIlCCxdkEQutcEWiG11JQHEwCLcB/s1600/test.ods.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="330" src="https://1.bp.blogspot.com/-ImNhZVsDOTE/V2GJYhXk1EI/AAAAAAAAC5g/_43JcdzUgLIlCCxdkEQutcEWiG11JQHEwCLcB/s640/test.ods.png" width="640" /></a></div>
<br />
- Export as csv file:<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://4.bp.blogspot.com/-10AcYElLpco/V2GJhjBouCI/AAAAAAAAC5o/_BuCjsj4o6gBcS6rSzLqMmJfvcC87iQZwCLcB/s1600/test.csv.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="330" src="https://4.bp.blogspot.com/-10AcYElLpco/V2GJhjBouCI/AAAAAAAAC5o/_BuCjsj4o6gBcS6rSzLqMmJfvcC87iQZwCLcB/s640/test.csv.png" width="640" /></a></div>
<br />
- The exported csv file in text format:<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://4.bp.blogspot.com/-TA2lEbgqwVQ/V2GJshQAaRI/AAAAAAAAC5w/Eo8sjIDJ5MEPNZ76PRUm09jVjpaTl-XygCLcB/s1600/test.csv.text.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="430" src="https://4.bp.blogspot.com/-TA2lEbgqwVQ/V2GJshQAaRI/AAAAAAAAC5w/Eo8sjIDJ5MEPNZ76PRUm09jVjpaTl-XygCLcB/s640/test.csv.text.png" width="640" /></a></div>
<br />
Using java to read the csv file and print the content:<br />
<pre class="brush: java">package javareadcsv;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @web http://java-buddy.blogspot.com/
*/
public class JavaReadCSV {
static String CsvFile = "/home/buddy/test/test.csv";
static String FieldDelimiter = ",";
public static void main(String[] args) throws IOException {
BufferedReader br;
try {
br = new BufferedReader(new FileReader(CsvFile));
String line;
while ((line = br.readLine()) != null) {
String[] fields = line.split(FieldDelimiter, -1);
System.out.print(fields.length + "-");
for(String s : fields){
System.out.print(s);
System.out.print(":");
}
System.out.println();
}
} catch (FileNotFoundException ex) {
Logger.getLogger(JavaReadCSV.class.getName())
.log(Level.SEVERE, null, ex);
}
}
}
</pre>
<br />
<br />
To display the content with JavaFX TableView, read <a href="http://java-buddy.blogspot.com/2016/06/read-csv-file-display-in-javafx.html">next post</a>.<br />
<br />Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-88460464662874341162016-06-07T16:56:00.001-07:002016-06-07T17:10:53.859-07:00Java example using Supplier to get input from ScannerJava example using java.util.function.Supplier to get input from java.util.Scanner.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://4.bp.blogspot.com/-LVKWi2A-bfg/V1ddALpqnOI/AAAAAAAAC5I/UnAExShjyeU1ao_lPVeCi-oOshMN2xYLACLcB/s1600/JavaSupplier.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="330" src="https://4.bp.blogspot.com/-LVKWi2A-bfg/V1ddALpqnOI/AAAAAAAAC5I/UnAExShjyeU1ao_lPVeCi-oOshMN2xYLACLcB/s640/JavaSupplier.png" width="640" /></a></div>
<br />
JavaSupplier.java
<br />
<pre class="brush: java">package javasupplier;
import java.util.Scanner;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class JavaSupplier {
public static void main(String[] args) {
Supplier<String> msg = ()-> "http://java-buddy.blogspot.com/";
System.out.println(msg.get());
System.out.println();
Scanner scanner = new Scanner(System.in);
Supplier<String> scannerNext = () -> scanner.next();
System.out.println("Enter something, 'q' to quit");
Stream.generate(scannerNext)
.map(s -> {
System.out.println(s);
return s;
})
.allMatch(s -> !"q".equals(s));
}
}
</pre>
<br />
<br />
<center>
<iframe allowfullscreen="" frameborder="0" height="360" src="https://www.youtube.com/embed/gami7F05NaI" width="640"></iframe>
</center>
Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-71226113900704913232016-04-17T04:59:00.000-07:002016-04-17T04:59:21.742-07:00Get my MAC address using NetworkInterfaceJava example to get MAC address using NetworkInterface:<br />
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-lBAE8zHvem4/VxN6M8R5pgI/AAAAAAAAC44/JB2kh2ItiooOzDk1HnEYJjq231XDPiiAQCLcB/s1600/get%2BMAC%2Baddress.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="328" src="https://2.bp.blogspot.com/-lBAE8zHvem4/VxN6M8R5pgI/AAAAAAAAC44/JB2kh2ItiooOzDk1HnEYJjq231XDPiiAQCLcB/s640/get%2BMAC%2Baddress.png" width="640" /></a></div>
<br />
<br />
<pre class="brush: java">package javamyip;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @web http://java-buddy.blogspot.com/
*/
public class JavaMyIP {
public static void main(String[] args) {
displayMyIP();
}
static void displayMyIP(){
Enumeration<NetworkInterface> nets;
try {
nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets)){
System.out.printf(netint.getDisplayName() +"\n");
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
System.out.printf("InetAddress: %s\n", inetAddress);
}
byte[] mac = netint.getHardwareAddress();
if(mac != null){
StringBuilder macAddr = new StringBuilder();
for (int i = 0; i < mac.length; i++) {
macAddr.append(String.format("%02X%s", mac[i], (i < mac.length - 1) ? ":" : ""));
}
System.out.printf("Hardware address (MAC): [%s]\n", macAddr.toString());
}
System.out.printf("\n");
}
} catch (SocketException ex) {
Logger.getLogger(JavaMyIP.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
</pre>
Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-18342674967070084972016-04-15T18:36:00.001-07:002016-04-15T18:38:26.664-07:00List my IP (inetAddress)<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-wBHZwmh4JEw/VxGV3_Ft6hI/AAAAAAAAC4o/FAojoAMZlFgaQAPJsDERBsTWDYNoiIpEgCLcB/s1600/JavaMyIP.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="328" src="https://2.bp.blogspot.com/-wBHZwmh4JEw/VxGV3_Ft6hI/AAAAAAAAC4o/FAojoAMZlFgaQAPJsDERBsTWDYNoiIpEgCLcB/s640/JavaMyIP.png" width="640" /></a></div>
<br />
Java example to list Network Interface Addresses and IP:<br />
<br />
<pre class="brush: java">package javamyip;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @web http://java-buddy.blogspot.com/
*/
public class JavaMyIP {
public static void main(String[] args) {
displayMyIP();
}
static void displayMyIP(){
Enumeration<NetworkInterface> nets;
try {
nets = NetworkInterface.getNetworkInterfaces();
for (NetworkInterface netint : Collections.list(nets)){
System.out.printf(netint.getDisplayName() +"\n");
Enumeration<InetAddress> inetAddresses = netint.getInetAddresses();
for (InetAddress inetAddress : Collections.list(inetAddresses)) {
System.out.printf("InetAddress: %s\n", inetAddress);
}
System.out.printf("\n");
}
} catch (SocketException ex) {
Logger.getLogger(JavaMyIP.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
</pre>
<br />
<br />
Can use functional operations in Java 8 (auto suggested by Netbeans):
<br />
<pre class="brush: java">package javamyip;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @web http://java-buddy.blogspot.com/
*/
public class JavaMyIP {
public static void main(String[] args) {
displayMyIP();
}
static void displayMyIP(){
Enumeration<NetworkInterface> nets;
try {
nets = NetworkInterface.getNetworkInterfaces();
Collections.list(nets).stream().map((netint) -> {
System.out.printf(netint.getDisplayName() +"\n");
return netint;
}).map((netint) -> netint.getInetAddresses()).map((inetAddresses) -> {
Collections.list(inetAddresses).stream().forEach((inetAddress) -> {
System.out.printf("InetAddress: %s\n", inetAddress);
});
return inetAddresses;
}).forEach((_item) -> {
System.out.printf("\n");
});
} catch (SocketException ex) {
Logger.getLogger(JavaMyIP.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
</pre>
<br />Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-11286576879579988102016-04-13T20:08:00.001-07:002016-04-13T20:10:17.475-07:00Create ServerSocket with automatically allocated portCreate ServerSocket by calling constructor <a href="https://docs.oracle.com/javase/8/docs/api/java/net/ServerSocket.html#ServerSocket-int-" target="_blank">ServerSocket(int port)</a> with port = 0, the port number is automatically allocated, typically from an ephemeral port range. This port number can then be retrieved by calling getLocalPort.<br />
<br />
Example:<br />
<pre class="brush: java">package javaechoserver;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaEchoServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
//Get a available port by passing 0
serverSocket = new ServerSocket(0);
int port = serverSocket.getLocalPort();
System.out.println("Port : " + port);
} catch (IOException ex) {
Logger.getLogger(JavaEchoServer.class.getName())
.log(Level.SEVERE, null, ex);
} finally {
if (serverSocket != null){
try {
serverSocket.close();
} catch (IOException ex) {
Logger.getLogger(JavaEchoServer.class.getName())
.log(Level.SEVERE, null, ex);
}
}
}
}
}
</pre>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-fcbh0FiQ4Iw/Vw8KCvx3NQI/AAAAAAAAC4U/mFrQNeuR9UIgdKnaJcHmqb_98jYIAV5JgCLcB/s1600/port.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="328" src="https://1.bp.blogspot.com/-fcbh0FiQ4Iw/Vw8KCvx3NQI/AAAAAAAAC4U/mFrQNeuR9UIgdKnaJcHmqb_98jYIAV5JgCLcB/s640/port.png" width="640" /></a></div>
<br />Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-50634557283117261502016-03-25T04:57:00.002-07:002016-03-25T04:57:48.607-07:00Mastering Concurrency Programming with Java 8Master the principles and techniques of multithreaded programming with the Java 8 Concurrency API<br />
<br />
<b><a href="http://www.amazon.com/gp/product/B012O8S89K/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B012O8S89K&linkCode=as2&tag=pointe&linkId=HVP5XVWCFZPYA4WW">Mastering Concurrency Programming with Java 8</a><img alt="" border="0" src="http://ir-na.amazon-adsystem.com/e/ir?t=pointe&l=as2&o=1&a=B012O8S89K" height="1" style="border: none !important; margin: 0px !important;" width="1" />
</b><br />
<br />
<b>About This Book</b><br />
<ul>
<li>Implement concurrent applications using the Java 8 Concurrency API and its new components</li>
<li>Improve the performance of your applications or process more data at the same time, taking advantage of all of your resources.</li>
<li>Construct real-world examples related to machine learning, data mining, image processing, and client/server environments</li>
</ul>
<b>Who This Book Is For</b><br />
If you are a competent Java developer with a good understanding of concurrency but have no knowledge of how to effectively implement concurrent programs or use streams to make processes more efficient, then this book is for you.<br />
<br />
<b>What You Will Learn</b><br />
<ul>
<li>Design concurrent applications by converting a sequential algorithm into a concurrent one</li>
<li>Discover how to avoid all the possible problems you can get in concurrent algorithms</li>
<li>Use the Executor framework to manage concurrent tasks without creating threads</li>
<li>Extend and modify Executors to adapt their behavior to your needs</li>
<li>Solve problems using the divide and conquer technique and the Fork/Join framework</li>
<li>Process massive data sets with parallel streams and Map/Reduce implementation</li>
<li>Control data-race conditions using concurrent data structures and synchronization mechanisms</li>
<li>Test and monitor concurrent applications</li>
</ul>
<b>In Detail</b><br />
Concurrency programming allows several large tasks to be divided into smaller sub-tasks, which are further processed as individual tasks that run in parallel. All the sub-tasks are combined together once the required results are achieved; they are then merged to get the final output. The whole process is very complex. This process goes from the design of concurrent algorithms to the testing phase where concurrent applications need extra attention. Java includes a comprehensive API with a lot of ready-to-use components to implement powerful concurrency applications in an easy way, but with a high flexibility to adapt these components to your needs.<br />
<br />
The book starts with a full description of design principles of concurrent applications and how to parallelize a sequential algorithm. We'll show you how to use all the components of the Java Concurrency API from basics to the most advanced techniques to implement them in powerful concurrency applications in Java.<br />
<br />
You will be using real-world examples of complex algorithms related to machine learning, data mining, natural language processing, image processing in client / server environments. Next, you will learn how to use the most important components of the Java 8 Concurrency API: the Executor framework to execute multiple tasks in your applications, the phaser class to implement concurrent tasks divided into phases, and the Fork/Join framework to implement concurrent tasks that can be split into smaller problems (using the divide and conquer technique). Toward the end, we will cover the new inclusions in Java 8 API, the Map and Reduce model, and the Map and Collect model. The book will also teach you about the data structures and synchronization utilities to avoid data-race conditions and other critical problems. Finally, the book ends with a detailed description of the tools and techniques that you can use to test a Java concurrent application.<br />
<br />
<b>Style and approach</b><br />
A complete guide implementing real-world examples with algorithms related to machine learning, data mining, and natural language processing in client/server environments. All the examples are explained in a step-by-step approach.<br />
<br />
<iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=pointe&marketplace=amazon&region=US&placement=B012O8S89K&asins=B012O8S89K&linkId=BF6X3XTFM752JHNL&show_border=true&link_opens_in_new_window=true" style="height: 240px; width: 120px;">
</iframe>Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-12411988307744115352016-03-14T17:08:00.001-07:002016-03-14T17:08:05.368-07:00JavaFX example: open new Window and exit all when primary window close<div class="separator" style="clear: both; text-align: center;">
<a href="https://4.bp.blogspot.com/-42Ec7tMTQEw/VudR49ez6pI/AAAAAAAAC4A/ep3BLM0RvkErAmrZW4Ul3zDtAxyuW7KcQ/s1600/JavaFXWindow.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="328" src="https://4.bp.blogspot.com/-42Ec7tMTQEw/VudR49ez6pI/AAAAAAAAC4A/ep3BLM0RvkErAmrZW4Ul3zDtAxyuW7KcQ/s640/JavaFXWindow.png" width="640" /></a></div>
<br />
JavaFX example to open new Window, and exit all when primary window close.<br />
<br />
<pre class="brush: java">package javafxwindow;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaFXWindow extends Application {
@Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Open a New Window");
btn.setOnAction((ActionEvent event) -> {
Label secondLabel = new Label("Hello");
StackPane secondaryLayout = new StackPane();
secondaryLayout.getChildren().add(secondLabel);
Scene secondScene = new Scene(secondaryLayout, 200, 100);
Stage secondStage = new Stage();
secondStage.setTitle("New Stage");
secondStage.setScene(secondScene);
secondStage.show();
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("java-buddy.blogspot.com");
primaryStage.setScene(scene);
primaryStage.show();
primaryStage.setOnCloseRequest(e -> Platform.exit());
}
public static void main(String[] args) {
launch(args);
}
}
</pre>
<br />
<center>
<iframe allowfullscreen="" frameborder="0" height="360" src="https://www.youtube.com/embed/K310akaJ40k" width="640"></iframe>
</center>
Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com1tag:blogger.com,1999:blog-1661517518925762010.post-92065179492059188702016-03-06T17:16:00.002-08:002016-03-06T17:22:39.843-08:00Read from Internet using URLConnection and BufferedReaderJava example to read from Internet using URLConnection and BufferedReader. <i>Thanks for Tomtom's comment in my last post "<a href="http://java-buddy.blogspot.com/2016/03/read-from-internet-using-urlconnection.html">Read from Internet using URLConnection and ReadableByteChannel</a>".</i><br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-x8qcocyW5G8/VtzXxSjwyGI/AAAAAAAAC3w/H-z4KiMPThY/s1600/URLConnection%2Band%2BBufferedReader.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="328" src="https://2.bp.blogspot.com/-x8qcocyW5G8/VtzXxSjwyGI/AAAAAAAAC3w/H-z4KiMPThY/s640/URLConnection%2Band%2BBufferedReader.png" width="640" /></a></div>
<br />
<br />
<pre class="brush: java">package javaurlconnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaURLConnection {
public static void main(String[] args) {
try {
URL url = new URL("http://java-buddy.blogspot.com");
URLConnection urlConnection = url.openConnection();
/*
InputStream inputStream = urlConnection.getInputStream();
try (ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream)) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (readableByteChannel.read(buffer) > 0)
{
String bufferString = new String(buffer.array());
System.out.println(bufferString);
buffer.clear();
}
}
*/
//using BufferedReader
InputStream inputStream = urlConnection.getInputStream();
InputStreamReader inputStreamReader =
new InputStreamReader(inputStream);
BufferedReader buffReader = new BufferedReader(inputStreamReader);
String line;
while ((line = buffReader.readLine()) != null) {
System.out.println(line);
}
} catch (MalformedURLException ex) {
Logger.getLogger(JavaURLConnection.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(JavaURLConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
</pre>
Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-38027642694685305782016-03-03T12:23:00.001-08:002016-03-06T17:17:52.556-08:00Read from Internet using URLConnection and ReadableByteChannelJava example to read from Internet, "http://java-buddy.blogspot.com", using URLConnection and ReadableByteChannel.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-Ax5gvHZGHK4/Vtic44ZiiGI/AAAAAAAAC3U/43UbQMLYkH4/s1600/URLConnection%2Band%2BReadableByteChannel.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="358" src="https://2.bp.blogspot.com/-Ax5gvHZGHK4/Vtic44ZiiGI/AAAAAAAAC3U/43UbQMLYkH4/s640/URLConnection%2Band%2BReadableByteChannel.png" width="640" /></a></div>
<br />
Example:
<br />
<pre class="brush: java">package javaurlconnection;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaURLConnection {
public static void main(String[] args) {
try {
URL url = new URL("http://java-buddy.blogspot.com");
URLConnection urlConnection = url.openConnection();
InputStream inputStream = urlConnection.getInputStream();
try (ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream)) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (readableByteChannel.read(buffer) > 0)
{
String bufferString = new String(buffer.array());
System.out.println(bufferString);
buffer.clear();
}
}
} catch (MalformedURLException ex) {
Logger.getLogger(JavaURLConnection.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(JavaURLConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
</pre>
<br />
<br />
Related:<br />
- <a href="http://java-buddy.blogspot.com/2016/03/read-from-internet-using-urlconnection_6.html">Read from Internet using URLConnection and BufferedReader</a> (Thanks Tomtom comment)<br />
<br />Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com2tag:blogger.com,1999:blog-1661517518925762010.post-53109204333957197062016-03-01T15:37:00.000-08:002016-03-01T15:37:06.403-08:00Get IP address of Website using InetAddressJava example to get IP address of Website using InetAddress:<br />
<br />
<pre class="brush: java">package javainetaddress;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaInetAddress {
public static void main(String[] args) {
try {
InetAddress inetAddress = InetAddress.getByName("www.google.com");
System.out.println(inetAddress);
System.out.println(inetAddress.getHostName());
System.out.println(inetAddress.getHostAddress());
} catch (UnknownHostException ex) {
Logger.getLogger(JavaInetAddress.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
</pre>
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-eUFpvsEXTMM/VtYnlIRxplI/AAAAAAAAC28/gTds6QAy-ZY/s1600/JavaInetAddress.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="328" src="https://2.bp.blogspot.com/-eUFpvsEXTMM/VtYnlIRxplI/AAAAAAAAC28/gTds6QAy-ZY/s640/JavaInetAddress.png" width="640" /></a></div>
<br />Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-20001724082789818212016-01-09T08:45:00.000-08:002016-01-09T08:48:49.062-08:00JavaFX example to capture screen/GUI nodes<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-fsNAkbeNt5E/VpE43Hts2wI/AAAAAAAAC2c/aWKjzWsSXLc/s1600/JavaFXCaptureScreen.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="328" src="http://3.bp.blogspot.com/-fsNAkbeNt5E/VpE43Hts2wI/AAAAAAAAC2c/aWKjzWsSXLc/s640/JavaFXCaptureScreen.png" width="640" /></a></div>
<br />
JavaFX example to capture screen/GUI nodes:
<br />
<pre class="brush: java">package javafxcapturescreen;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Button;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaFXCaptureScreen extends Application {
@Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
Scene scene = new Scene(root, 300, 250);
Button btnCaptureScene = new Button();
btnCaptureScene.setText("Capture scene");
btnCaptureScene.setOnAction((ActionEvent event) -> {
WritableImage writableImage = scene.snapshot(null);
File file = new File("capturedScene.png");
try {
ImageIO.write(SwingFXUtils.fromFXImage(writableImage, null), "png", file);
System.out.println("Captured: " + file.getAbsolutePath());
} catch (IOException ex) {
Logger.getLogger(JavaFXCaptureScreen.class.getName()).log(Level.SEVERE, null, ex);
}
});
Button btnCaptureRoot = new Button();
btnCaptureRoot.setText("Capture root");
btnCaptureRoot.setOnAction((ActionEvent event) -> {
WritableImage writableImage = root.snapshot(new SnapshotParameters(), null);
File file = new File("capturedRoot.png");
try {
ImageIO.write(SwingFXUtils.fromFXImage(writableImage, null), "png", file);
System.out.println("Captured: " + file.getAbsolutePath());
} catch (IOException ex) {
Logger.getLogger(JavaFXCaptureScreen.class.getName()).log(Level.SEVERE, null, ex);
}
});
VBox vBox = new VBox();
vBox.getChildren().addAll(btnCaptureScene, btnCaptureRoot);
root.getChildren().add(vBox);
primaryStage.setTitle("java-buddy.blogspot.com");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
</pre>
<br />
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://4.bp.blogspot.com/-DTAs-HZzsiM/VpE5cEz5tvI/AAAAAAAAC2k/avzAtQu8LY0/s1600/capturedScene.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" src="http://4.bp.blogspot.com/-DTAs-HZzsiM/VpE5cEz5tvI/AAAAAAAAC2k/avzAtQu8LY0/s1600/capturedScene.png" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">capturedScene.png</td></tr>
</tbody></table>
<br />
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="http://1.bp.blogspot.com/-KUzDNgYrqXU/VpE5cCdUmGI/AAAAAAAAC2o/E9TGiM5JZuI/s1600/capturedRoot.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" src="http://1.bp.blogspot.com/-KUzDNgYrqXU/VpE5cCdUmGI/AAAAAAAAC2o/E9TGiM5JZuI/s1600/capturedRoot.png" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">capturedRoot.png</td></tr>
</tbody></table>
<br />Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-2002754258595001592016-01-07T08:29:00.002-08:002016-01-07T08:33:05.421-08:00Capture screen using java.awt.RobotJava example to capture screen using java.awt.Robot:<br />
<br />
<pre class="brush: java">package javarobotcapturescreen;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaRobotCaptureScreen {
public static void main(String[] args) {
try {
Robot robot = new Robot();
Toolkit myToolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = myToolkit.getScreenSize();
Rectangle screen = new Rectangle(screenSize);
BufferedImage screenFullImage = robot.createScreenCapture(screen);
ImageIO.write(screenFullImage, "jpg", new File("screen.jpg"));
} catch (AWTException | IOException ex) {
Logger.getLogger(JavaRobotCaptureScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
</pre>
<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-inRMF7gewJY/Vo6SaUce-kI/AAAAAAAAC2E/A3tR6pINllc/s1600/JavaRobotCaptureScreen.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="328" src="http://1.bp.blogspot.com/-inRMF7gewJY/Vo6SaUce-kI/AAAAAAAAC2E/A3tR6pINllc/s640/JavaRobotCaptureScreen.png" width="640" /></a></div>
<br />
captured screen:<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-wvo4JiSWpbM/Vo6TKAifftI/AAAAAAAAC2M/9w-slhts8QQ/s1600/screen.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="328" src="http://3.bp.blogspot.com/-wvo4JiSWpbM/Vo6TKAifftI/AAAAAAAAC2M/9w-slhts8QQ/s640/screen.jpg" width="640" /></a></div>
<br />Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-84265142505529705872016-01-07T02:25:00.001-08:002016-01-07T02:25:29.024-08:00Get screen size and resolution, with java.awt.ToolkitJava example to get screen size and resolution, with java.awt.Toolkit:<br />
<br />
<pre class="brush: java">package javagetscreensize;
import java.awt.Dimension;
import java.awt.Toolkit;
/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaGetScreenSize {
public static void main(String[] args) {
Toolkit myToolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = myToolkit.getScreenSize();
int screenResolution = myToolkit.getScreenResolution();
System.out.println("Screen size = " + screenSize.width + " x " + screenSize.height);
System.out.println("Screen Resolution: " + screenResolution + " dots-per-inch");
}
}
</pre>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-snY4I9zy0ek/Vo48xgBUJ8I/AAAAAAAAC10/KA3BEZVThdk/s1600/java%2Bget%2Bscreen%2Bsize.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="328" src="http://1.bp.blogspot.com/-snY4I9zy0ek/Vo48xgBUJ8I/AAAAAAAAC10/KA3BEZVThdk/s640/java%2Bget%2Bscreen%2Bsize.png" width="640" /></a></div>
<br />Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-44158832247571597182016-01-07T01:07:00.000-08:002016-01-07T01:07:04.485-08:00Java Everywhere: Write Once run Anywhere with DukeScript<b><a href="http://www.amazon.com/gp/product/B019Y6QFKY/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=B019Y6QFKY&linkCode=as2&tag=pointe&linkId=3CWYYDHWVSRYLDUT" rel="nofollow">Java Everywhere: Write Once run Anywhere with DukeScript</a><img alt="" border="0" src="http://ir-na.amazon-adsystem.com/e/ir?t=pointe&l=as2&o=1&a=B019Y6QFKY" height="1" style="border: none !important; margin: 0px !important;" width="1" />
</b><br />
<br />
Do you want to write Java apps that run on mobile phones, tablets as well as your desktop computer? In this book you'll learn how to design and develop apps and upload them to Google Play and Apples App Store. The technology we'll use for that is DukeScript, a new framework for single-source cross-platform development in Java.<br />
<br />
<iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=pointe&marketplace=amazon&region=US&placement=B019Y6QFKY&asins=B019Y6QFKY&linkId=NQVPKKO3ZKS76RMT&show_border=true&link_opens_in_new_window=true" style="height: 240px; width: 120px;">
</iframe>Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-4141609716962779132015-12-28T07:19:00.000-08:002015-12-28T07:20:34.293-08:00Files.lines() read text file returned by JavaFX FileChooserExample show how to read all lines from a file returned by JavaFX FileChooser, using <a href="https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#lines-java.nio.file.Path-" target="_blank">Files.lines()</a>.<br />
<br />
<center>
<iframe allowfullscreen="" frameborder="0" height="360" src="https://www.youtube.com/embed/Zpv4mtzeknU" width="640"></iframe>
</center>
<br />
<pre class="brush: java">package javafxreadtextfile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaFXReadTextFile extends Application {
@Override
public void start(Stage primaryStage) {
Button btnLoad = new Button("Load");
btnLoad.setOnAction(btnLoadEventListener);
VBox rootBox = new VBox();
rootBox.getChildren().add(btnLoad);
Scene scene = new Scene(rootBox, 300, 300);
primaryStage.setTitle("java-buddy.blogspot.com");
primaryStage.setScene(scene);
primaryStage.show();
}
EventHandler<ActionEvent> btnLoadEventListener
= (ActionEvent event) -> {
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters()
.addAll(
new FileChooser.ExtensionFilter("TXT files (*.TXT)", "*.TXT"),
new FileChooser.ExtensionFilter("txt files (*.txt)", "*.txt"));
File file = fileChooser.showOpenDialog(null);
if (file != null) {
try {
Files.lines(file.toPath()).forEach(System.out::println);
} catch (IOException ex) {
Logger.getLogger(JavaFXReadTextFile.class.getName())
.log(Level.SEVERE, null, ex);
}
}
};
public static void main(String[] args) {
launch(args);
}
}
</pre>
<br />Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-50822916155444477862015-12-06T12:10:00.001-08:002015-12-06T12:29:32.883-08:00JavaFX FileChooser to open image file, and display on ImageView, run on Ubuntu GNOME 15.10/NetBeans 8.1Re-test "<a href="http://java-buddy.blogspot.com/2013/01/use-javafx-filechooser-to-open-image.html">Use JavaFX FileChooser to open image file, and display on ImageView</a>" on Ubuntu GNOME 15.10/NetBeans 8.1.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-KArY5SDljN4/VmSUle70uII/AAAAAAAAC1k/GOULfhA_5xg/s1600/JavaFxPixel.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="328" src="http://4.bp.blogspot.com/-KArY5SDljN4/VmSUle70uII/AAAAAAAAC1k/GOULfhA_5xg/s640/JavaFxPixel.png" width="640" /></a></div>
<br />
<center>
<iframe allowfullscreen="" frameborder="0" height="360" src="https://www.youtube.com/embed/Q51_dlZ55Ro" width="640"></iframe>
</center>
<br />
<pre class="brush: java">package javafxpixel;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
/**
* @web http://java-buddy.blogspot.com/
*/
public class JavaFxPixel extends Application {
ImageView myImageView;
@Override
public void start(Stage primaryStage) {
Button btnLoad = new Button("Load");
btnLoad.setOnAction(btnLoadEventListener);
myImageView = new ImageView();
VBox rootBox = new VBox();
rootBox.getChildren().addAll(btnLoad, myImageView);
Scene scene = new Scene(rootBox, 300, 300);
primaryStage.setTitle("java-buddy.blogspot.com");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
EventHandler<ActionEvent> btnLoadEventListener
= new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent t) {
FileChooser fileChooser = new FileChooser();
//Set extension filter
FileChooser.ExtensionFilter extFilterJPG =
new FileChooser.ExtensionFilter("JPG files (*.JPG)", "*.JPG");
FileChooser.ExtensionFilter extFilterjpg =
new FileChooser.ExtensionFilter("jpg files (*.jpg)", "*.jpg");
FileChooser.ExtensionFilter extFilterPNG =
new FileChooser.ExtensionFilter("PNG files (*.PNG)", "*.PNG");
FileChooser.ExtensionFilter extFilterpng =
new FileChooser.ExtensionFilter("png files (*.png)", "*.png");
fileChooser.getExtensionFilters()
.addAll(extFilterJPG, extFilterjpg, extFilterPNG, extFilterpng);
//Show open file dialog
File file = fileChooser.showOpenDialog(null);
try {
BufferedImage bufferedImage = ImageIO.read(file);
Image image = SwingFXUtils.toFXImage(bufferedImage, null);
myImageView.setImage(image);
} catch (IOException ex) {
Logger.getLogger(JavaFxPixel.class.getName()).log(Level.SEVERE, null, ex);
}
}
};
}
</pre>
Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-1095749307988881012015-11-11T12:17:00.000-08:002015-11-11T12:27:10.417-08:00Query InterNIC server's whoisLast example show <a href="http://java-buddy.blogspot.com/2015/11/java-example-using-whoisclient-class.html">Java example using WhoisClient class</a> to query whois. Alternatively, we can query InterNIC server's whois without WhoisClient class.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-TJ3vHvC32j4/VkOh8zb7-kI/AAAAAAAAC1U/30qfZ6mO5NY/s1600/JavaWhoIs.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="358" src="http://1.bp.blogspot.com/-TJ3vHvC32j4/VkOh8zb7-kI/AAAAAAAAC1U/30qfZ6mO5NY/s640/JavaWhoIs.png" width="640" /></a></div>
<br />
<pre class="brush: java">package javawhois;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @web http://java-buddy.blogspot.com/
*/
public class JavaWhoIs {
private final static String WHO ="google.com";
private final static String WHOIS_HOST = "whois.internic.net";
private final static int WHOIS_PORT = 43;
public static void main(String[] args) {
int c;
Socket socket = null;
String query = "=" + WHO + "\r\n";
byte buf[] = query.getBytes();
try {
socket = new Socket(WHOIS_HOST, WHOIS_PORT);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
out.write(buf);
out.flush();
while ((c = in.read()) != -1) {
System.out.print((char) c);
}
System.out.print("\nDone\n");
} catch (IOException ex) {
Logger.getLogger(JavaWhoIs.class.getName()).log(Level.SEVERE, null, ex);
System.out.print(ex.getMessage());
} finally {
if(socket != null){
try {
socket.close();
} catch (IOException ex) {
Logger.getLogger(JavaWhoIs.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
</pre>
<br />
<center>
<iframe allowfullscreen="" frameborder="0" height="360" src="https://www.youtube.com/embed/HKIIwAq-itw" width="640"></iframe>
</center>
Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-76128422850305597122015-11-08T21:48:00.002-08:002015-11-11T12:21:42.765-08:00Java example using WhoisClient classThe WhoisClient class implements the client side of the Internet Whois Protocol defined in RFC 954. To query a host you create a WhoisClient instance, connect to the host, query the host, and finally disconnect from the host. If the whois service you want to query is on a non-standard port, connect to the host at that port.<br />
~ <a href="https://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/whois/WhoisClient.html" target="_blank">org.apache.commons.net.whois.WhoisClient</a><br />
<br />
Example:<br />
<pre class="brush: java">package javawhoisclient;
import java.io.IOException;
import org.apache.commons.net.whois.WhoisClient;
/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaWhoisClient {
public static void main(String[] args) {
WhoisClient whois;
whois = new WhoisClient();
try {
whois.connect(WhoisClient.DEFAULT_HOST);
System.out.println(whois.query("=google.com"));
whois.disconnect();
} catch (IOException e) {
System.err.println("Error I/O exception: " + e.getMessage());
return;
}
}
}
</pre>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-eGS9xX7UbnE/VkAzi-qZ-ZI/AAAAAAAAC1A/pAxd4fl94KQ/s1600/java%2BWhoisClient.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="358" src="http://2.bp.blogspot.com/-eGS9xX7UbnE/VkAzi-qZ-ZI/AAAAAAAAC1A/pAxd4fl94KQ/s640/java%2BWhoisClient.png" width="640" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-_ceG5tvgjeg/VkAzi4CgBoI/AAAAAAAAC08/3pM6_Od2QSk/s1600/java%2BWhoisClient%2Boutput.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="358" src="http://4.bp.blogspot.com/-_ceG5tvgjeg/VkAzi4CgBoI/AAAAAAAAC08/3pM6_Od2QSk/s640/java%2BWhoisClient%2Boutput.png" width="640" /></a></div>
<br />
To use WhoisClient class in your program, you have to include library commons-net-3.3 in your code, it can be download here: <a href="https://commons.apache.org/proper/commons-net/index.html" target="_blank">https://commons.apache.org/proper/commons-net/index.html</a><br />
<br />
This video show how to download and add library commons-net-3.3 to NetBeans IDE.<br />
<br />
<center>
<iframe allowfullscreen="" frameborder="0" height="360" src="https://www.youtube.com/embed/DtPz0hQcNvA" width="640"></iframe>
</center>
<br />
Next:<br />
- <a href="http://java-buddy.blogspot.com/2015/11/query-internic-servers-whois.html">query InterNIC server's whois without WhoisClient class</a>.<br />
<br />Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-6506143084951084432015-11-08T02:46:00.001-08:002015-11-08T02:57:05.108-08:00Install Netbeans 8.1 0n Ubuntu 15.10Netbeans IDE 8.1 just released.<br />
<div>
<br /></div>
<div>
This video show how to download and install Netbeans IDE 8.1 on Ubuntu-GNOME 15.10<br />
<div>
<br /></div>
<center>
<iframe allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/RZVUTCmpKVE" width="560"></iframe>
</center>
<div>
<br />
To install Ubuntu 8.1 on Ubuntu:</div>
<div>
- Visit <a href="https://netbeans.org/" target="_blank">https://netbeans.org/</a> to download installer-file.</div>
<div>
- chmod +x <installer-file-name>.</div>
<div>
- run it with command:</div>
<div>
./<installer-file-name> to run the installer.</div>
<div>
<br /></div>
</div>
<div>
The only special is to select correct path to JDK, 1:40 in the above video.</div>
<div>
<br /></div>
<div>
<a href="http://java-buddy.blogspot.com/2015/10/install-oracle-java-8-on-ubuntu-1510.html">My JDK was installed with ppa:webupd8team</a>, it's on "/usr/lib/jvm/java-8-oracle".</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-rcyK4nrlxlE/Vj8lJkrJFUI/AAAAAAAAC0s/CIPABhZ8UGk/s1600/Install%2BNetbeans%2Bon%2BUbuntu.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="223" src="http://4.bp.blogspot.com/-rcyK4nrlxlE/Vj8lJkrJFUI/AAAAAAAAC0s/CIPABhZ8UGk/s400/Install%2BNetbeans%2Bon%2BUbuntu.png" width="400" /></a></div>
<br />
<br />
<hr />
If you missed the setting JDK path, you still run edit netbeans.conf, to specify netbeans_jdkhome, or run netbeans with --jdkhome option. (ref: <a href="http://wiki.netbeans.org/FaqRunningOnJre" target="_blank">http://wiki.netbeans.org/FaqRunningOnJre</a>)<br />
<br />
netbeans.conf to set netbeans_jdkhome:
<br />
<br />
<center>
<iframe allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/lBrD-gsEMdc" width="560"></iframe>
</center>
<br />
<br />
run netbeans with --jdkhome option:
<br />
<br />
<center>
<iframe allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/WaWc4Ju6IG0" width="560"></iframe>
</center>
<br />Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-46366410454549489642015-11-05T21:35:00.000-08:002015-11-05T21:35:04.409-08:00JavaOne Keynote Highlights 10-25-2015<center>
<iframe allowfullscreen="" frameborder="0" height="239" marginheight="0" marginwidth="0" scrolling="no" src="//www.slideshare.net/slideshow/embed_code/key/3qKrfMK2shKmiw" style="border-width: 1px; border: 1px solid #CCC; margin-bottom: 5px; max-width: 100%;" width="425"> </iframe> <div style="margin-bottom: 5px;">
<strong> <a href="https://www.slideshare.net/oracle/javaone-keynote-highlights-10252015-54800005" target="_blank" title="JavaOne Keynote Highlights 10-25-2015">JavaOne Keynote Highlights 10-25-2015</a> </strong> from <strong><a href="https://www.slideshare.net/oracle" target="_blank">Oracle</a></strong> </div>
</center>
<br />
<br />Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-33660151946168595452015-11-05T20:19:00.003-08:002015-11-05T20:19:45.418-08:00Java I/O, NIO and NIO.2<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-N5I8_3gymZ8/VjwqF9WHy_I/AAAAAAAAC0g/JoOqlfe3mR8/s1600/Java%2BIO%252C%2BNIO%2Band%2BNIO.2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="http://1.bp.blogspot.com/-N5I8_3gymZ8/VjwqF9WHy_I/AAAAAAAAC0g/JoOqlfe3mR8/s320/Java%2BIO%252C%2BNIO%2Band%2BNIO.2.jpg" width="210" /></a></div>
<br />
<b>
<a href="http://www.amazon.com/gp/product/1484215664/ref=as_li_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1484215664&linkCode=as2&tag=pointe&linkId=BAMKBBOZ3DVN2PUC" rel="nofollow">Java I/O, NIO and NIO.2</a><img alt="" border="0" src="http://ir-na.amazon-adsystem.com/e/ir?t=pointe&l=as2&o=1&a=1484215664" height="1" style="border: none !important; margin: 0px !important;" width="1" />
</b><br />
<br />
Java I/O, NIO, and NIO.2 is a power-packed book that accelerates your mastery of Java's various I/O APIs. In this book, you'll learn about classic I/O APIs (File, RandomAccessFile, the stream classes and related types, and the reader/writer classes). Next, you'll learn about NIO's buffer, channel, selector, regular expression, charset, and formatter APIs. Finally, you'll discover NIO.2's offerings in terms of an improved file system interface, asynchronous I/O, and the completion of socket channel functionality.<br />
<br />
After reading and using thi book, you'll gain the accelerated knowledge and skill level to really build applications with efficient data access, especially for today's cloud computing streaming data needs.<br />
<br />
<b>What you’ll learn</b><br />
<ul>
<li>How to set permissions and more with the classic File class</li>
<li>How to build a flat file database with RandomAccessFile</li>
<li>Get to know the byte array, file, filter, and other kinds of streams</li>
<li>Master serialization and externalization</li>
<li>Discover character streams and their associated writers/readers</li>
<li>Tour the buffer APIs</li>
<li>Work with channels to transfer buffers to and from I/O services</li>
<li>Find out about selectors and readiness selection</li>
<li>Master regular expressions</li>
<li>Discover charsets and their association with Java's String< class</li>
<li>Take advantage of the formatter API to create formatted output</li>
<li>How to customize the formatter API</li>
<li>Explore the improved file system interface</li>
<li>Discover asynchronous I/O and its association with futures and completion handlers</li>
<li>Encounter socket channel improvements, including multicasting</li>
</ul>
<b>Who this book is for</b><br />
This book is for those experienced with Java, beyond the fundamentals.<br />
<br />
<b>Table of Contents</b><br />
<b>Part 1: Getting Started with I/O</b><br />
Chapter 1: I/O Basics and APIs<br />
<b>Part 2: Classic I/O APIs</b><br />
Chapter 2: File<br />
Chapter 3: RandomAccessFile<br />
Chapter 4: Streams<br />
Chapter 5: Writers and Readers<br />
<b>Part 3: New I/O APIs</b><br />
Chapter 6: Buffers<br />
Chapter 7: Channels<br />
Chapter 8: Selectors<br />
Chapter 9: Regular Expressions<br />
Chapter 10: Charsets<br />
Chapter 11: Formatter and Scanner<br />
<b>Part 4: More New I/O APIs</b><br />
Chapter 12: File System APIs<br />
Chapter 13: Asynchronous I/O<br />
Chapter 14: Additional NIO.2 APIs<br />
Appendix A: Answers to Review Exercises<br />
<br />
<iframe frameborder="0" marginheight="0" marginwidth="0" scrolling="no" src="//ws-na.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&OneJS=1&Operation=GetAdHtml&MarketPlace=US&source=ac&ref=tf_til&ad_type=product_link&tracking_id=pointe&marketplace=amazon&region=US&placement=1484215664&asins=1484215664&linkId=WU7YI2LAUCZ4IYNU&show_border=true&link_opens_in_new_window=true" style="height: 240px; width: 120px;">
</iframe>Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0tag:blogger.com,1999:blog-1661517518925762010.post-14216135067857603842015-10-29T21:16:00.000-07:002015-10-29T21:16:02.661-07:00Install java-gnome on Ubuntu 15.10, and first try.The <a href="http://java-gnome.sourceforge.net/" target="_blank">java-gnome User Interface Library</a> is a Java bindings for GTK and GNOME. To install it on Ubuntu, enter the command in Terminal:<br />
<b>$ sudo apt-get install libjava-gnome-java</b><br />
<br />
<center>
<iframe allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/mgu_8jPccY8" width="560"></iframe>
</center>
<br />
(reference: <a href="http://java-gnome.sourceforge.net/get/ubuntu.php" target="_blank">http://java-gnome.sourceforge.net/get/ubuntu.php</a>)<br />
<br />
First try:<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-qsIhwChkmS8/VjLtwe7Al4I/AAAAAAAAC0Q/KLejatCR-Kw/s1600/ExamplePressMe.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="111" src="http://4.bp.blogspot.com/-qsIhwChkmS8/VjLtwe7Al4I/AAAAAAAAC0Q/KLejatCR-Kw/s320/ExamplePressMe.png" width="320" /></a></div>
<br />
<br />
Create a my first example ExamplePressMe.java (copt from <a href="http://java-gnome.sourceforge.net/doc/examples/button/ExamplePressMe.html" target="_blank">HERE</a>), under trial directory ~/java-gnome-works.
<br />
<pre class="brush: java">/*
* ExamplePressMe.java
*
* Copyright (c) 2006-2008 Operational Dynamics Consulting Pty Ltd
*
* The code in this file, and the library it is a part of, are made available
* to you by the authors under the terms of the "GNU General Public Licence,
* version 2" See the LICENCE file for the terms governing usage and
* redistribution.
*/
package button;
import org.gnome.gdk.Event;
import org.gnome.gtk.Button;
import org.gnome.gtk.Gtk;
import org.gnome.gtk.Label;
import org.gnome.gtk.VBox;
import org.gnome.gtk.Widget;
import org.gnome.gtk.Window;
/**
* A simple Window with a Label and a Button in it. Demonstrates the basics of
* initializing GTK, packing Widgets into Containers, and hooking up signals.
*
* This example has been around, in one form or another, since the very
* beginnings of java-gnome. If you're just starting out with GTK and GNOME
* don't worry; we started here too.
*
* @author Andrew Cowie
* @since 4.0.0
*/
public class ExamplePressMe
{
public static void main(String[] args) {
final Window w;
final VBox x;
final Label l;
final Button b;
/*
* Initialize GTK. You MUST call this to load the library before
* trying to use any other elements provided by java-gnome.
*/
Gtk.init(args);
/*
* Create a top level Window. It's the Container around which the
* window manager draws decorations such as a title bar, minimize and
* close buttons, resize edges, etc.
*/
w = new Window();
/*
* Since a Window is a Bin, it can only have one child Widget. That's
* probably not very useful in most cases. To take that one slot and
* turn it into many, we use a VBox, a Container that will stack its
* children vertically.
*/
x = new VBox(false, 3);
/*
* Create a Label with some text describing the Button that will
* follow, then add it to the VBox.
*/
l = new Label("Go ahead:\nMake my day");
x.add(l);
/*
* Create our Button, with a nice explicit bit of text labelling it
* and what you're to do.
*/
b = new Button("Press me!");
x.add(b);
/*
* Now the magic part. Just sitting there, the Button won't do
* anything. You need to hook up a "signal handler" to deal with the
* 'clicked' signal. This is how we do it in java-gnome.
*
* Button.Clicked is a Java interface. You create an instance of it to
* do what you want when the callback happens, and then pass it to the
* Button's connect() method.
*
* The onClicked() method is what is required by the Button.Clicked
* interface. Most IDEs will prompt you asking if you want to "Add
* unimplemented methods?" You bet! And ta-da! You have exactly the
* signature you need to implement a 'clicked' signal handler.
*
* Since we declared b as final we can use it in the anonymous nested
* class (yet *another* reason that final is worth using). If the
* situation were otherwise, then the source parameter can be used to
* find out what Button was clicked.
*/
b.connect(new Button.Clicked() {
public void onClicked(Button source) {
System.out.println("I was clicked: " + b.getLabel());
}
});
/*
* Now we pack the VBox into our Window, set the Window's title, and
* invoke the command to realize everything onto the screen.
*/
w.add(x);
w.setTitle("Hello World");
w.showAll();
/*
* We would be be done except for one last detail. Closing a Window
* does not terminate the application. If that's what you want (and we
* do indeed want that here) then you need to hook up a handler to do
* something when the 'delete-event' signal is emitted.
*
* Again, the method here implements the interface.
*/
w.connect(new Window.DeleteEvent() {
public boolean onDeleteEvent(Widget source, Event event) {
Gtk.mainQuit();
return false;
}
});
/*
* Now we're ready to run the main loop. The signals we've hooked up
* handlers for above won't be emitted until the user does something,
* but no events will be processed until the main loop is running;
* that's where the signals will come from. This call blocks. You have
* finished setting things up and now it's up to your signal handlers
* to carry out the program's logic in response to the user's actions;
* the essence of event-driven programming.
*/
Gtk.main();
}
}
</pre>
<br />
<br />
Make a tests directory to hold the output.<br />
<br />
Enter the command to compile the java code with java-gnome.<br />
<b>$ javac -classpath /usr/share/java/gtk-4.1.jar -d tests ExamplePressMe.java</b><br />
<br />
Run it:<br />
<b>$ java -classpath /usr/share/java/gtk-4.1.jar:tests button.ExamplePressMe</b><br />
<br />
Where /usr/share/java/gtk-4.1.jar is the installed gtk-4.1.jar.<br />
<br />
<center>
<iframe allowfullscreen="" frameborder="0" height="315" src="https://www.youtube.com/embed/sHGkTKEFOGM" width="560"></iframe>
</center>
<br />
(reference: <a href="http://java-gnome.sourceforge.net/README.html" target="_blank">http://java-gnome.sourceforge.net/README.html</a>)<br />
<br />Anonymoushttp://www.blogger.com/profile/02036390354033315722noreply@blogger.com0