jSSC - java serial port communication library, java-simple-serial-connector, is a library for working with serial ports from Java. jSSC support Win32(Win98-Win8), Win64, Linux(x86, x86-64, ARM), Solaris(x86, x86-64), Mac OS X 10.5 and higher(x86, x86-64, PPC, PPC64). Documentation and examples you can find in wiki.
https://code.google.com/p/java-simple-serial-connector/
All new downloads will be available on GitHub: https://github.com/scream3r/java-simple-serial-connector/releases
Install, setup for NetBeans IDE and example: https://code.google.com/p/java-simple-serial-connector/wiki/jSSC_Start_Working
Friday, February 28, 2014
Wednesday, February 26, 2014
Return an array from method
This example show how to return an array from method. And also show that we can change the source array inside method.
Return an array from method |
package java_array; /** * * @web http://java-buddy.blogspot.com/ */ public class Java_Array { public static void main(String[] args) { int orgInt = 5; float returnFloat = intMethod(orgInt); System.out.println("original int no changed: " + orgInt); System.out.println("float return from method: " + returnFloat); int[] orgArray = new int[]{1, 2, 3, 4, 5}; System.out.println(); System.out.println("Original array defore calling method"); for(int i=0; i<orgArray.length; i++){ System.out.println(orgArray[i]); } float[] returnArray = arrayMethod(orgArray); System.out.println(); System.out.println("Original array changed in method"); for(int i=0; i<orgArray.length; i++){ System.out.println(orgArray[i]); } System.out.println(); System.out.println("Array of float returned from method"); for(int i=0; i<returnArray.length; i++){ System.out.println(returnArray[i]); } } static private float[] arrayMethod(int[] src){ float[] result = new float[src.length]; for(int i=0; i<src.length; i++){ result[i] = (float)src[i]; src[i] = src[i] * src[i]; } return result; } static private float intMethod(int src){ float result = src; src = src * src; return result; } }
Tuesday, February 25, 2014
Update JavaFX UI in scheduled task, of Thread(Task), Thread(Runnable) and Timer with TimerTask
This example implement scheduled task, of Thread(Task), Thread(Runnable) and Timer with TimerTask. To update JavaFX UI ProgressBar.
package javafx_timertask; import java.util.Timer; import java.util.TimerTask; import java.util.logging.Level; import java.util.logging.Logger; import javafx.application.Application; import javafx.application.Platform; import javafx.concurrent.Task; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.layout.StackPane; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * * @web http://java-buddy.blogspot.com/ */ public class JavaFX_TimerTask extends Application { final int MAX = 100; Thread myTaskThread; Thread myRunnableThread; Timer myTimer; MyTask myTask; MyRunnable myRunnable; MyTimerTask myTimerTask; @Override public void start(Stage primaryStage) { myTask = new MyTask(); ProgressBar progressBarTask = new ProgressBar(); progressBarTask.setProgress(0); progressBarTask.progressProperty().bind(myTask.progressProperty()); ProgressBar progressBarRunnable = new ProgressBar(); progressBarRunnable.setProgress(0); myRunnable = new MyRunnable(progressBarRunnable); ProgressBar progressBarTimerTask = new ProgressBar(); progressBarTimerTask.setProgress(0); myTimerTask = new MyTimerTask(progressBarTimerTask); Button btnStart = new Button("Start Task"); btnStart.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent t) { myTaskThread = new Thread(myTask); myTaskThread.start(); myRunnableThread = new Thread(myRunnable); myRunnableThread.start(); myTimer = new Timer(); myTimer.scheduleAtFixedRate(myTimerTask, 0, 100); } }); VBox vBox = new VBox(); vBox.setPadding(new Insets(5, 5, 5, 5)); vBox.setSpacing(5); vBox.getChildren().addAll( new Label("Run in Thread(Task)"), progressBarTask, new Label("Run in Thread(Runnable)"), progressBarRunnable, new Label("Run in Timer and TimerTask"), progressBarTimerTask, btnStart); StackPane root = new StackPane(); root.getChildren().add(vBox); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("java-buddy.blogspot.com"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { launch(args); } class MyTask extends Task<Void>{ @Override protected Void call() throws Exception { for (int i = 1; i <= MAX; i++) { updateProgress(i, MAX); Thread.sleep(100); } return null; } } class MyRunnable implements Runnable{ ProgressBar bar; public MyRunnable(ProgressBar b) { bar = b; } @Override public void run() { for (int i = 1; i <= MAX; i++) { final double update_i = i; //Not work if update JavaFX UI here! //bar.setProgress(i/MAX); //Update JavaFX UI with runLater() in UI thread Platform.runLater(new Runnable(){ @Override public void run() { bar.setProgress(update_i/MAX); } }); try { Thread.sleep(100); } catch (InterruptedException ex) { Logger.getLogger(JavaFX_TimerTask.class.getName()).log(Level.SEVERE, null, ex); } } } } class MyTimerTask extends TimerTask{ ProgressBar bar; double count; public MyTimerTask(ProgressBar b) { bar = b; count = 0; } @Override public void run() { bar.setProgress(count++/MAX); if(count >= MAX){ myTimer.cancel(); } } } }
Sunday, February 23, 2014
Get parameters/arguments in JavaFX application
When you start a JavaFX application, main() will not be called (I don't know the logic behind)! To Retrieves the parameters for this Application, including any arguments, we can call getParameters() method of javafx.application.Application class. getParameters() return a Application.Parameters. We can retrieve the parameters and arguments with its getNamed(), getRaw() or getUnnamed():
You can start the JavaFX application, JavaFX_Hello, in command line to pass named parameters with something like:
$ java -jar JavaFX_Hello.jar --width=320 --name=Java-Buddy
- Map<String, String> getNamed():
Retrieves a read-only map of the named parameters. - List<String> getRaw():
Retrieves a read-only list of the raw arguments. - List<String> getUnnamed():
Retrieves a read-only list of the unnamed parameters.
package javafx_hello; import java.util.List; import java.util.Map; 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.StackPane; import javafx.stage.Stage; /** * * @web http://java-buddy.blogspot.com/ */ public class JavaFX_Hello extends Application { @Override public void init() throws Exception { super.init(); System.out.println("init()"); Parameters parameters = getParameters(); Map<String, String> namedParameters = parameters.getNamed(); List<String> rawArguments = parameters.getRaw(); List<String> unnamedParameters = parameters.getUnnamed(); System.out.println("\nnamedParameters -"); for (Map.Entry<String,String> entry : namedParameters.entrySet()) { System.out.println(entry.getKey() + " : " + entry.getValue()); } System.out.println("\nrawArguments -"); for(String raw : rawArguments) { System.out.println(raw); } System.out.println("\nunnamedParameters -"); for(String unnamed : unnamedParameters) { System.out.println(unnamed); } } @Override public void start(Stage primaryStage) { Button btn = new Button(); btn.setText("Say 'Hello World'"); btn.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { System.out.println("Hello World!"); } }); StackPane root = new StackPane(); root.getChildren().add(btn); Scene scene = new Scene(root, 300, 250); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); } public static void main(String[] args) { System.out.println("main()"); launch(args); } }
You can start the JavaFX application, JavaFX_Hello, in command line to pass named parameters with something like:
$ java -jar JavaFX_Hello.jar --width=320 --name=Java-Buddy
Saturday, February 22, 2014
Java EE 7 Developer Handbook
Develop professional applications in Java EE 7 with this essential reference guide
Overview
- Learn about local and remote service endpoints, containers, architecture, synchronous and asynchronous invocations, and remote communications in a concise reference
- Understand the architecture of the Java EE platform and then apply the new Java EE 7 enhancements to benefit your own business-critical applications
- Learn about integration test development on Java EE with Arquillian Framework and the Gradle build system
- Learn about containerless builds featuring the GlassFish 4.0 embedded application server
- Master Java EE 7 with this example-based, up-to-date guide with descriptions and explanations
In Detail
The seventh edition of the Enterprise Java platform is aimed at helping Java engineers take advantage of the advancements in HTML5 and web standards. Web Sockets, asynchronous input and output with Servlets, and strong type safety through the CDI containers will ensure that Java EE 7 remains popular for server-side applications.
If you are a user aiming to get acquainted with the Java EE 7 platform, this book is for you.
"Java EE 7 Handbook" provides a solid foundation of knowledge for developers to build business applications. Following the lead of Agile practices, there is a focus on writing tests to demonstrate test-driven development principles, using the embedded GlassFish 4.0 container examples and the Gradle build system. You will learn about CDI, EJB, JPA, JMS, MDB, Servlets, WebSocket, JAX-RS, Bean Validation, and so much more.
"Java EE 7 Handbook" is designed as a companion to the professional software developer who quickly needs to lookup some working code, understand the basics of the framework, and then go out and fulfill the business contract with the customer. Typically, engineers are under pressure to develop professional code that is of high quality and contains a low number of bugs. Java EE 7 Handbook relies heavily on the Arquillian framework to illustrate how much easier it is to write Java EE tests, and together with the modern practice of writing containerless applications that actually embed an application container, developing agile Java EE suddenly becomes reasonable, smart, pragmatic, and achievable.
What you will learn from this book
- Understand the JSR and the API that are assembled together for Java EE 7
- Write server side and client side WebSocket connection in Java
- Understand the essential differences and similarities between the EJB and CDI containers, as well as dependency injection
- Learn about Gradle builds, embedded containers, and the Arquillian Framework
- Build server side endpoints with EJB in stateless, stateful, and singleton modes
- Write REST server side endpoints on the client and server side
- Write asynchronous Servlet input and output and also annotated Servlet, Context Listeners
- Map entities in Java Persistence with the essential cardinalities including the Java side of many-to-many relationships
- Learn about mapping entities to stored procedures and entity graphs
- Fully understand how to verify your POJO before they hit the database with Bean Validation API
- Be prepared for the Java EE 8 journey and beyond, which may include deployment to the cloud
Saturday, February 15, 2014
Simple example of UDP Client/Server communication
It's a simple example to implement UDP Client/Server in Java. To test the function, start JavaUDPServer with port number in Terminal. The server will open a DatagramSocket and wait for incoming message from client. Then start JavaUDPClient with IP address and port number in another Terminal, then enter anything. The user input will be sent to JavaUDPServer via UDP socket, when JavaUDPServer receive the message, it will echo back to JavaUDPClient, then both JavaUDPServer and JavaUDPClient close the socket.
JavaUDPServer.java
JavaUDPClient.java
Compare with: Simple example of TCP Client/Server communication
JavaUDPServer |
JavaUDPClient |
JavaUDPServer.java
package javaudpserver; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.util.logging.Level; import java.util.logging.Logger; /** * * @web http://java-buddy.blogspot.com/ */ public class JavaUDPServer { private static DatagramSocket datagramSocket; private static final int BUFFER_SIZE = 1024; private static byte[] buffer; public static void main(String[] args) { if (args.length != 1) { System.out.println("usage: java -jar JavaUDPServer.jar <port>"); System.exit(1); } int port = Integer.parseInt(args[0]); System.out.println("Port: " + port); try { datagramSocket = new DatagramSocket(port); buffer = new byte[BUFFER_SIZE]; DatagramPacket in_datagramPacket = new DatagramPacket( buffer, BUFFER_SIZE); datagramSocket.receive(in_datagramPacket); InetAddress clientAddress = in_datagramPacket.getAddress(); int clientPort = in_datagramPacket.getPort(); String in_message = new String( in_datagramPacket.getData(), 0, in_datagramPacket.getLength()); System.out.println("received: " + in_message); String out_messagae = "echo: " + in_message; DatagramPacket out_datagramPacket= new DatagramPacket( out_messagae.getBytes(), out_messagae.length(), clientAddress, clientPort); datagramSocket.send(out_datagramPacket); } catch (SocketException ex) { Logger.getLogger(JavaUDPServer.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(JavaUDPServer.class.getName()).log(Level.SEVERE, null, ex); } finally { datagramSocket.close(); } } }
JavaUDPClient.java
package javaudpclient; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @web http://java-buddy.blogspot.com/ */ public class JavaUDPClient { private static DatagramSocket datagramSocket; private static final int BUFFER_SIZE = 1024; private static byte[] buffer; public static void main(String[] args) { if (args.length != 2) { System.out.println("usage: java -jar JavaUDPClient.jar <IP address> <port>"); System.exit(1); } try { InetAddress inetAddress = InetAddress.getByName(args[0]); int port = Integer.parseInt(args[1]); Scanner userScanner = new Scanner(System.in); String userInput = userScanner.nextLine(); datagramSocket = new DatagramSocket(); DatagramPacket out_datagramPacket = new DatagramPacket( userInput.getBytes(), userInput.length(), inetAddress, port); datagramSocket.send(out_datagramPacket); buffer = new byte[BUFFER_SIZE]; DatagramPacket in_datagramPacket = new DatagramPacket(buffer, BUFFER_SIZE); datagramSocket.receive(in_datagramPacket); String serverEcho = new String( in_datagramPacket.getData(), 0, in_datagramPacket.getLength()); System.out.println(serverEcho); } catch (UnknownHostException ex) { Logger.getLogger(JavaUDPClient.class.getName()).log(Level.SEVERE, null, ex); } catch (SocketException ex) { Logger.getLogger(JavaUDPClient.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(JavaUDPClient.class.getName()).log(Level.SEVERE, null, ex); } finally { datagramSocket.close(); } } }
Compare with: Simple example of TCP Client/Server communication
Friday, February 14, 2014
Simple but useful app to test your page speed
SimplePageSpeed is a simple app to test the performance of your web page.
Google PageSpeed Insights analyzes the content of a web page, then generates suggestions to make that page faster.
The app fetch simple test result for any page from Google PageSpeed Insights. The results include:
- PageSpeed score
- Top PageSpeed suggestions
- Resource size breakdown
It's a useful tool for webmaster to test performance of any webpage.
Google PageSpeed Insights analyzes the content of a web page, then generates suggestions to make that page faster.
The app fetch simple test result for any page from Google PageSpeed Insights. The results include:
- PageSpeed score
- Top PageSpeed suggestions
- Resource size breakdown
It's a useful tool for webmaster to test performance of any webpage.
Simple example of TCP Client/Server communication
It's a simple example to implement TCP Client/Server in Java. To test the function, start JavaTCPServer with port number in Terminal. The server will open a ServerSocket and wait for incoming message from client. Then start JavaTCPClient with IP address and port number in another Terminal, then enter anything. The user input will be sent to JavaTCPServer via TCP socket, when JavaTCPServer receive the message, it will echo back to JavaTCPClient, then both JavaTCPServer and JavaTCPClient close the socket.
JavaTCPServer.java
JavaTCPClient.java
Compare with: Simple example of UDP Client/Server communication
TCP Client/Server communication |
JavaTCPServer.java
package javatcpserver; import java.io.IOException; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @web http://java-buddy.blogspot.com/ */ public class JavaTCPServer { private static int port; private static ServerSocket serverSocket; public static void main(String[] args) { if (args.length != 1) { System.out.println("usage: java -jar JavaTCPServer.jar <port>"); System.exit(1); } port = Integer.parseInt(args[0]); System.out.println("Port: " + port); Socket socket = null; try { serverSocket = new ServerSocket(port); socket = serverSocket.accept(); Scanner scanner = new Scanner(socket.getInputStream()); PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true); String line = scanner.nextLine(); System.out.println("received: " + line); printWriter.println("echo: " + line); } catch (IOException ex) { Logger.getLogger(JavaTCPServer.class.getName()).log(Level.SEVERE, null, ex); } finally { if (socket != null) { try { socket.close(); } catch (IOException ex) { Logger.getLogger(JavaTCPServer.class.getName()).log(Level.SEVERE, null, ex); } } } } }
JavaTCPClient.java
package javatcpclient; import java.io.IOException; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; /** * * @web http://java-buddy.blogspot.com/ */ public class JavaTCPClient { public static void main(String[] args) { if (args.length != 2) { System.out.println("usage: java -jar JavaTCPClient.jar <IP address> <port>"); System.exit(1); } Socket socket = null; try { InetAddress inetAddress = InetAddress.getByName(args[0]); int port = Integer.parseInt(args[1]); socket = new Socket(inetAddress, port); System.out.println("InetAddress: " + inetAddress); System.out.println("Port: " + port); Scanner scanner = new Scanner(socket.getInputStream()); PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true); Scanner userScanner = new Scanner(System.in); String userInput = userScanner.nextLine(); printWriter.println(userInput); String serverEcho = scanner.nextLine(); System.out.println(serverEcho); } catch (UnknownHostException ex) { Logger.getLogger(JavaTCPClient.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(JavaTCPClient.class.getName()).log(Level.SEVERE, null, ex); } finally { if( socket != null){ try { socket.close(); } catch (IOException ex) { Logger.getLogger(JavaTCPClient.class.getName()).log(Level.SEVERE, null, ex); } } } } }
Compare with: Simple example of UDP Client/Server communication
Get address of local host with InetAddress.getLocalHost()
- InetAddress.getLocalHost() returns the address of the local host. This is achieved by retrieving the name of the host from the system, then resolving that name into an InetAddress.
InetAddress.getLocalHost() |
package javaexnetworking; 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 JavaExNetworking { public static void main(String[] args) { try { InetAddress localHostAddress = InetAddress.getLocalHost(); System.out.println(localHostAddress); } catch (UnknownHostException ex) { Logger.getLogger(JavaExNetworking.class.getName()).log(Level.SEVERE, null, ex); } } }
Get IP address of a host using InetAddress.getByName() and getAllByName()
- InetAddress.getByName(String host) return the IP address of a host, given the host's name.
- InetAddress.getAllByName(String host) returns an array of its IP addresses, based on the configured name service on the system.
using InetAddress.getByName() and getAllByName() |
package javaexnetworking; 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 JavaExNetworking { public static void main(String[] args) { String host = "www.google.com"; System.out.println("by InetAddress.getByName(host):"); try { InetAddress inetAddress = InetAddress.getByName(host); System.out.println(inetAddress.toString()); } catch (UnknownHostException ex) { Logger.getLogger(JavaExNetworking.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("\nby InetAddress.getAllByName(host):"); try { InetAddress[] allInetAddress = InetAddress.getAllByName(host); for(int i=0; i<allInetAddress.length; i++){ System.out.println(allInetAddress[i].toString()); } } catch (UnknownHostException ex) { Logger.getLogger(JavaExNetworking.class.getName()).log(Level.SEVERE, null, ex); } } }
Thursday, February 13, 2014
Simple example to display message dialog with JOptionPane
The showMessageDialog(Component parentComponent, Object message) method of JOptionPane display an information-message dialog.
where:
parentComponent - determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is used.
message - the Object to display
where:
parentComponent - determines the Frame in which the dialog is displayed; if null, or if the parentComponent has no Frame, a default Frame is used.
message - the Object to display
display message dialog with JOptionPane |
package javajoptionpane; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingUtilities; /** * * @web http://java-buddy.blogspot.com/ */ public class JavaJOptionPane extends JFrame{ public void prepareUI() { JPanel hPanel = new JPanel(); hPanel.setLayout(new BoxLayout(hPanel, BoxLayout.X_AXIS)); JButton jButton = new JButton("showMessageDialog"); jButton.setVerticalTextPosition(JButton.BOTTOM); jButton.setHorizontalTextPosition(JButton.RIGHT); jButton.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog( null, "It's JOptionPane"); } }); hPanel.add(jButton); getContentPane().add(hPanel, BorderLayout.CENTER); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI() { JavaJOptionPane myJavaJOptionPane = new JavaJOptionPane(); myJavaJOptionPane.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myJavaJOptionPane.prepareUI(); myJavaJOptionPane.pack(); myJavaJOptionPane.setVisible(true); } }
Monday, February 10, 2014
Install JDK8 Release Candidate on Raspberry Pi
The first Release Candidate build of JDK 8, b128 is available now. It Including supported platform of Linux ARMv6/7 VFP, HardFP ABI, it can be run on Raspberry Pi. Here show the steps to install on Raspberry Pi.
http://helloraspberrypi.blogspot.com/2014/02/java-8-release-candidate-is-available.html
http://helloraspberrypi.blogspot.com/2014/02/java-8-release-candidate-is-available.html
標籤:
Java 8,
JDK,
JDK8,
Raspberry Pi
Sunday, February 9, 2014
Get OS name and OS architecture (actually JVM architecture) using Java code
To get OS name (something like Windows 7, Linux, ...) and OS architecture (like amd64, x86, i386, ...), we can call the method System.getProperty() with parameter of "os.name" and "os.arch".
example:
But, please note that System.getProperty("os.arch") actually return JVM architecture, not OS architecture. read more: Beware when detecting 32 and 64 bit OS's in Java
example:
Get OS name and OS architecture (actually JVM architecture) |
package javaosarch; public class JavaOsArch { public static void main(String[] args) { System.out.println("OS name : "+System.getProperty("os.name")); System.out.println("OS arch : "+System.getProperty("os.arch")); } }
But, please note that System.getProperty("os.arch") actually return JVM architecture, not OS architecture. read more: Beware when detecting 32 and 64 bit OS's in Java
Saturday, February 8, 2014
NetBeans IDE 8.0 Beta, working with Java 8
NetBeans IDE 8.0 Beta provides out-of-the-box code analyzers and editors for working with the latest Java 8 technologies--Java SE 8, Java SE Embedded 8, and Java ME Embedded 8. The IDE also has a range of new enhancements that further improve its support for Maven and Java EE with PrimeFaces; new tools for HTML5, in particular for AngularJS; and improvements to PHP and C/C++ support.
https://netbeans.org/community/releases/80/
https://netbeans.org/community/releases/80/
Wednesday, February 5, 2014
Migration to JDK 8
Smart Migration to JDK 8
A thorough guide to the key features of language enhancements in Java 8, especially lambdas, functional operations, and method references.
A thorough guide to the key features of language enhancements in Java 8, especially lambdas, functional operations, and method references.
Tuesday, February 4, 2014
Monday, February 3, 2014
Java Swing example: Add and Remove UI components dynamically
This example show add and remove UI compnents in run-time dynamically:
Add and Remove UI components dynamically |
package javadynui; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; /** * * @web http://java-buddy.blogspot.com/ */ public class JavaDynUI extends JFrame { static JavaDynUI myFrame; static int countMe = 0; JPanel mainPanel; public static void main(String[] args) { SwingUtilities.invokeLater(() -> { createAndShowGUI(); }); } private static void createAndShowGUI() { myFrame = new JavaDynUI(); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.prepareUI(); myFrame.pack(); myFrame.setVisible(true); } private void prepareUI() { mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); JButton buttonAdd = new JButton("Add subPanel"); buttonAdd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { mainPanel.add(new subPanel()); myFrame.pack(); } }); JButton buttonRemoveAll = new JButton("Remove All"); buttonRemoveAll.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { mainPanel.removeAll(); myFrame.pack(); } }); getContentPane().add(mainPanel, BorderLayout.CENTER); getContentPane().add(buttonAdd, BorderLayout.PAGE_START); getContentPane().add(buttonRemoveAll, BorderLayout.PAGE_END); } private class subPanel extends JPanel { subPanel me; public subPanel() { super(); me = this; JLabel myLabel = new JLabel("Hello subPanel(): " + countMe++); add(myLabel); JButton myButtonRemoveMe = new JButton("remove me"); myButtonRemoveMe.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { me.getParent().remove(me); myFrame.pack(); } }); add(myButtonRemoveMe); } } }
Java Swing example: insert UI dynamically
This example show inserting UI compnents in run-time dynamically:
Insert UI dynamically |
package javadynui; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; /** * * @web http://java-buddy.blogspot.com/ */ public class JavaDynUI extends JFrame { static JavaDynUI myFrame; static int countMe = 0; JPanel mainPanel; public static void main(String[] args) { SwingUtilities.invokeLater(() -> { createAndShowGUI(); }); } private static void createAndShowGUI() { myFrame = new JavaDynUI(); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.prepareUI(); myFrame.pack(); myFrame.setVisible(true); } private void prepareUI() { mainPanel = new JPanel(); mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS)); JButton buttonAdd = new JButton("Add subPanel"); buttonAdd.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { mainPanel.add(new subPanel()); myFrame.pack(); } }); getContentPane().add(mainPanel, BorderLayout.CENTER); getContentPane().add(buttonAdd, BorderLayout.PAGE_START); } private class subPanel extends JPanel { public subPanel() { super(); JLabel myLabel = new JLabel("Hello subPanel(): " + countMe++); add(myLabel); } } }
Saturday, February 1, 2014
Example of using JInternalFrame
JInternalFrame example |
package javaswingjinternalframe; import javax.swing.JDesktopPane; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.SwingUtilities; public class JavaSwingJInternalFrame extends JFrame { JDesktopPane desktop; public JavaSwingJInternalFrame() { super("Java-Buddy"); int inset = 50; setBounds(inset, inset, 500, 400); desktop = new JDesktopPane(); createFrame(); createFrame(50, 100); setContentPane(desktop); } private void createFrame() { MyInternalFrame frame = new MyInternalFrame(); frame.setVisible(true); desktop.add(frame); try { frame.setSelected(true); } catch (java.beans.PropertyVetoException e) { } } private void createFrame(int x, int y) { MyInternalFrame frame = new MyInternalFrame(x, y); frame.setVisible(true); desktop.add(frame); try { frame.setSelected(true); } catch (java.beans.PropertyVetoException e) { } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI() { JavaSwingJInternalFrame myFrame = new JavaSwingJInternalFrame(); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.setVisible(true); } private class MyInternalFrame extends JInternalFrame { public MyInternalFrame() { super("MyInternalFrame", true, //resizable true, //closable true, //maximizable true);//iconifiable setSize(300, 200); } public MyInternalFrame(int offsetX, int offsetY) { super("MyInternalFrame", true, //resizable true, //closable true, //maximizable true);//iconifiable setSize(300, 200); setLocation(offsetX, offsetY); } } }
Subscribe to:
Posts (Atom)