Showing posts with label code snap. Show all posts
Showing posts with label code snap. Show all posts

Saturday, August 16, 2014

Java CountDownLatch and Thread

Example to use java.util.concurrent.CountDownLatch, synchronization aid that allows one or more threads to wait until a set of operations being performed in other threads completes.


package javacountdownlatch;

import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaCountDownLatch {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
        System.out.println("Start counting");
        
        CountDownLatch countDownLatch1 = new CountDownLatch(5);
        CountThread countThread1 = new CountThread("A", countDownLatch1, 5);
        CountDownLatch countDownLatch2 = new CountDownLatch(7);
        CountThread countThread2 = new CountThread("B", countDownLatch2, 7);

        try {
            countDownLatch1.await();
            System.out.println("A finished");
            countDownLatch2.await();
            System.out.println("B finished");
        } catch (InterruptedException ex) {
            Logger.getLogger(JavaCountDownLatch.class.getName()).log(Level.SEVERE, null, ex);
            System.out.println(ex.toString());
        }
    }
}

class CountThread implements Runnable {

    int num_of_count = 5;
    CountDownLatch counter;
    String name;

    CountThread(String n, CountDownLatch c, int num) {
        name = n;
        counter = c;
        num_of_count = num;
        new Thread(this).start();
    }

    @Override
    public void run() {

        for (int i = 0; i < num_of_count; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(CountThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println(name + " : " + counter.getCount());
            counter.countDown();
        }
    }

}


- Read JavaFX version, Bind JavaFX ProgressBar.progressProperty() to DoubleProperty in Thread.

Monday, March 3, 2014

JavaFX + java-simple-serial-connector + Arduino



A simple Java application using java-simple-serial-connector library (jSSC) , with JavaFX user interface, send bytes to Arduino Esplora via USB.

http://arduino-er.blogspot.com/2014/03/javafx-java-simple-serial-connector.html

Example of using AudioSystem to play wav file

The javax.sound.sampled.AudioSystem class acts as the entry point to the sampled-audio system resources.

Example to play wav file using AudioSystem:
package javafx_audio;

import java.io.File;
import java.io.IOException;
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.StackPane;
import javafx.stage.Stage;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaFX_Audio extends Application {
    
    @Override
    public void start(Stage primaryStage) {
        Button btn = new Button();
        btn.setText("Play 'Hello World'");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            
            @Override
            public void handle(ActionEvent event) {
                System.out.println("Hello World!");
                playSound();
            }
        });
        
        StackPane root = new StackPane();
        root.getChildren().add(btn);
        
        Scene scene = new Scene(root, 300, 250);
        
        primaryStage.setTitle("java-buddy");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
    
    private void playSound(){
        AudioInputStream audio = null;
        try {
            String clipPath = "/home/eric/tmp/HelloWorld.wav";
            audio = AudioSystem.getAudioInputStream(new File(clipPath));
            Clip clip = AudioSystem.getClip();
            clip.open(audio);
            clip.start();
        } catch (UnsupportedAudioFileException ex) {
            Logger.getLogger(JavaFX_Audio.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JavaFX_Audio.class.getName()).log(Level.SEVERE, null, ex);
        } catch (LineUnavailableException ex) {
                Logger.getLogger(JavaFX_Audio.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                audio.close();
            } catch (IOException ex) {
                Logger.getLogger(JavaFX_Audio.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

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


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():

  • 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.
Example:

getParameters()
Example of using getParameters()


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 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

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 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.

TCP 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()
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()

using InetAddress.getByName() and getAllByName()
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

JOptionPane
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 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
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
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
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);
        }
    }

}

Sunday, January 26, 2014

JavaFX/Swing + RxTx to communicate with Arduino, as ColorPicker

Here is examples from arduino-er.blogspot.com to demonstrate how to use RxTx Java Library in JavaFX/Swing application to communicate with Arduino Esplora via USB serial. javafx.scene.control.ColorPicker/javax.swing.JColorChooser are used to choice color, then send to Arduino via USB serial with RxTx Java Library, then to set the color of LCD screen/LED in Arduino side.

JavaFX version:
package javafxcolorpicker;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import javafx.application.Application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.ColorPicker;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class JavaFXColorPicker extends Application {

    MyRxTx myRxTx;

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("ColorPicker");
        final Scene scene = new Scene(new HBox(20), 400, 100);
        HBox box = (HBox) scene.getRoot();
        box.setPadding(new Insets(5, 5, 5, 5));

        final ColorPicker colorPicker = new ColorPicker();
        //colorPicker.setValue(Color.CORAL);

        colorPicker.setOnAction(new EventHandler() {
            public void handle(Event t) {
                scene.setFill(colorPicker.getValue());
                
                Color color = colorPicker.getValue();
                byte byteR = (byte)(color.getRed() * 255);
                byte byteG = (byte)(color.getGreen() * 255);
                byte byteB = (byte)(color.getBlue() * 255);
                
                try {
                    byte[] bytesToSent = 
                            new byte[]{byteB, byteG, byteR};
                    myRxTx.output.write(bytesToSent);
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        });

        box.getChildren().add(colorPicker);

        primaryStage.setScene(scene);
        primaryStage.show();
        
        myRxTx = new MyRxTx();
        myRxTx.initialize();
    }

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

    class MyRxTx implements SerialPortEventListener {

        SerialPort serialPort;
        /**
         * The port we're normally going to use.
         */
        private final String PORT_NAMES[] = {
            "/dev/ttyACM0", //for Ubuntu
            "/dev/tty.usbserial-A9007UX1", // Mac OS X
            "/dev/ttyUSB0", // Linux
            "COM3", // Windows
        };
        private BufferedReader input;
        private OutputStream output;
        private static final int TIME_OUT = 2000;
        private static final int DATA_RATE = 9600;

        public void initialize() {
            CommPortIdentifier portId = null;
            Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

            //First, Find an instance of serial port as set in PORT_NAMES.
            while (portEnum.hasMoreElements()) {
                CommPortIdentifier currPortId
                        = (CommPortIdentifier) portEnum.nextElement();
                for (String portName : PORT_NAMES) {
                    if (currPortId.getName().equals(portName)) {
                        portId = currPortId;
                        break;
                    }
                }
            }
            if (portId == null) {
                System.out.println("Could not find COM port.");
                return;
            } else {
                System.out.println("Port Name: " + portId.getName() + "\n"
                        + "Current Owner: " + portId.getCurrentOwner() + "\n"
                        + "Port Type: " + portId.getPortType());
            }

            try {
                // open serial port, and use class name for the appName.
                serialPort = (SerialPort) portId.open(this.getClass().getName(),
                        TIME_OUT);

                // set port parameters
                serialPort.setSerialPortParams(DATA_RATE,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);

                // open the streams
                input = new BufferedReader(
                        new InputStreamReader(serialPort.getInputStream()));
                output = serialPort.getOutputStream();

                // add event listeners
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }

        @Override
        public void serialEvent(SerialPortEvent spe) {
            if (spe.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                try {
                    final String inputLine = input.readLine();
                    System.out.println(inputLine);
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }
        }

        /**
         * This should be called when you stop using the port. This will prevent
         * port locking on platforms like Linux.
         */
        public synchronized void close() {
            if (serialPort != null) {
                serialPort.removeEventListener();
                serialPort.close();
            }
        }
    }

}



Java Swing version:
package javaswingcolorpicker;

import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Enumeration;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JFrame;

public class JavaSwingColorPicker extends JFrame {
    
    MyRxTx myRxTx;

    public JavaSwingColorPicker() {
        super("JColorChooser Test Frame");
        setSize(200, 100);
        final Container contentPane = getContentPane();
        final JButton go = new JButton("Show JColorChooser");
        go.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Color c;
                c = JColorChooser.showDialog(
                        ((Component) e.getSource()).getParent(),
                        "Demo", Color.blue);
                contentPane.setBackground(c);

                byte byteR = (byte)(c.getRed());
                byte byteG = (byte)(c.getGreen());
                byte byteB = (byte)(c.getBlue() );
                
                try {
                    byte[] bytesToSent = 
                            new byte[]{byteB, byteG, byteR};
                    myRxTx.output.write(bytesToSent);
                    
                } catch (IOException ex) {
                    System.out.println(ex.toString());
                }
            }
        });
        contentPane.add(go, BorderLayout.SOUTH);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        
        myRxTx = new MyRxTx();
        myRxTx.initialize();
    }

    public static void main(String[] args) {
        JavaSwingColorPicker myColorPicker = new JavaSwingColorPicker();
        myColorPicker.setVisible(true);
        
    }

    class MyRxTx implements SerialPortEventListener {

        SerialPort serialPort;
        /**
         * The port we're normally going to use.
         */
        private final String PORT_NAMES[] = {
            "/dev/ttyACM0", //for Ubuntu
            "/dev/tty.usbserial-A9007UX1", // Mac OS X
            "/dev/ttyUSB0", // Linux
            "COM3", // Windows
        };
        private BufferedReader input;
        private OutputStream output;
        private static final int TIME_OUT = 2000;
        private static final int DATA_RATE = 9600;

        public void initialize() {
            CommPortIdentifier portId = null;
            Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

            //First, Find an instance of serial port as set in PORT_NAMES.
            while (portEnum.hasMoreElements()) {
                CommPortIdentifier currPortId
                        = (CommPortIdentifier) portEnum.nextElement();
                for (String portName : PORT_NAMES) {
                    if (currPortId.getName().equals(portName)) {
                        portId = currPortId;
                        break;
                    }
                }
            }
            if (portId == null) {
                System.out.println("Could not find COM port.");
                return;
            } else {
                System.out.println("Port Name: " + portId.getName() + "\n"
                        + "Current Owner: " + portId.getCurrentOwner() + "\n"
                        + "Port Type: " + portId.getPortType());
            }

            try {
                // open serial port, and use class name for the appName.
                serialPort = (SerialPort) portId.open(this.getClass().getName(),
                        TIME_OUT);

                // set port parameters
                serialPort.setSerialPortParams(DATA_RATE,
                        SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);

                // open the streams
                input = new BufferedReader(
                        new InputStreamReader(serialPort.getInputStream()));
                output = serialPort.getOutputStream();

                // add event listeners
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }

        @Override
        public void serialEvent(SerialPortEvent spe) {
            if (spe.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
                try {
                    final String inputLine = input.readLine();
                    System.out.println(inputLine);
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }
        }

        /**
         * This should be called when you stop using the port. This will prevent
         * port locking on platforms like Linux.
         */
        public synchronized void close() {
            if (serialPort != null) {
                serialPort.removeEventListener();
                serialPort.close();
            }
        }
    }

}



For the code in Arduino side, refer: http://arduino-er.blogspot.com/2014/01/send-array-of-byte-from-pc-to-arduino.html

Tuesday, January 21, 2014

JButton with Icon

JButton with Icon
JButton with Icon

package javaexample;

import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaExample extends JFrame {

    public void prepareUI() {
        JPanel hPanel = new JPanel();
        hPanel.setLayout(new BoxLayout(hPanel, BoxLayout.X_AXIS));
        
        ImageIcon dukesIcon = null;
        java.net.URL imgURL = JavaExample.class.getResource("dukes_36x36.png");
        if (imgURL != null) {
            dukesIcon = new ImageIcon(imgURL);
        } else {
            System.err.println("Can't load icon! ");
        }

        JButton jButton = new JButton("java-buddy.blogspot.com",
                            dukesIcon);
        jButton.setVerticalTextPosition(JButton.BOTTOM);
        jButton.setHorizontalTextPosition(JButton.RIGHT);

        hPanel.add(jButton);
        getContentPane().add(hPanel, BorderLayout.CENTER);
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        JavaExample myExample = new JavaExample();
        myExample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myExample.prepareUI();
        myExample.pack();
        myExample.setVisible(true);
    }
    
}

Monday, January 20, 2014

Example to create JLabel with icon

JLabel with icon
JLabel with icon

package javaexample;

import java.awt.BorderLayout;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaExample extends JFrame {

    public void prepareUI() {
        JPanel hPanel = new JPanel();
        hPanel.setLayout(new BoxLayout(hPanel, BoxLayout.X_AXIS));
        
        ImageIcon dukesIcon = null;
        java.net.URL imgURL = JavaExample.class.getResource("dukes_36x36.png");
        if (imgURL != null) {
            dukesIcon = new ImageIcon(imgURL);
        } else {
            System.err.println("Can't load icon! ");
        }

        JLabel jLabel = new JLabel("java-buddy.blogspot.com",
                            dukesIcon,
                            JLabel.CENTER);
        jLabel.setVerticalTextPosition(JLabel.BOTTOM);
        jLabel.setHorizontalTextPosition(JLabel.CENTER);

        hPanel.add(jLabel);
        getContentPane().add(hPanel, BorderLayout.CENTER);
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        JavaExample myExample = new JavaExample();
        myExample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myExample.prepareUI();
        myExample.pack();
        myExample.setVisible(true);
    }
    
}

Thursday, January 16, 2014

Java Swing example using Border

Java Swing example using Border

package javaswingborder;

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.AbstractBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.MatteBorder;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaSwingBorder extends JFrame 
    implements ListSelectionListener{

    JList jList;
    JLabel jLabelInfo;
    
    static final String borderTypeArray[] = {
        "Bevel", 
        "Compound", 
        "Empty", 
        "Etched", 
        "Line", 
        "Matte", 
        "SoftBevel",
        "Titled" };
    
    AbstractBorder[] borderArray = {
        new BevelBorder(BevelBorder.LOWERED),
        new CompoundBorder(
                new LineBorder(Color.blue, 10), 
                new LineBorder(Color.red, 5)),
        new EmptyBorder(10, 10, 10, 10), 
        new EtchedBorder(), 
        new LineBorder(Color.blue, 10),
        new MatteBorder(5, 10, 5, 10, Color.GREEN), 
        new SoftBevelBorder(BevelBorder.RAISED),
        new TitledBorder("TitledBorder") };

    private void prepareUI() {
        
        JPanel hPanel = new JPanel();
        hPanel.setLayout(new BoxLayout(hPanel, BoxLayout.X_AXIS));
        
        jList = new JList(borderTypeArray);
        jList.addListSelectionListener(this);
        hPanel.add(jList);
        jLabelInfo = new JLabel("java-buddy.blogspot.com");
        hPanel.add(jLabelInfo);

        getContentPane().add(hPanel, BorderLayout.CENTER);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }

    private static void createAndShowGUI() {
        JavaSwingBorder myFrame = new JavaSwingBorder();
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.prepareUI();
        myFrame.pack();
        myFrame.setVisible(true);
    }

    @Override
    public void valueChanged(ListSelectionEvent e) {
        int selectedIndex = jList.getSelectedIndex();
        String selectedType = (String)jList.getSelectedValue();
        jLabelInfo.setText(selectedType);
        jLabelInfo.setBorder(borderArray[selectedIndex]);
    }

}

Wednesday, January 8, 2014

Java example of using JPopupMenu

JPopupMenu
JPopupMenu

package javamenu;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMenu extends JFrame {

    JLabel jLabel;
    JPopupMenu jPopupMenu;

    private void prepareUI() {

        jLabel = new JLabel("Label", JLabel.RIGHT);
        getContentPane().add(jLabel);

        jPopupMenu = new JPopupMenu();
        JMenuItem jMenuItem_A = new JMenuItem("Menu Item A");
        JMenuItem jMenuItem_B = new JMenuItem("Menu Item B");
        JMenuItem jMenuItem_C = new JMenuItem("Menu Item C");
        jPopupMenu.add(jMenuItem_A);
        jPopupMenu.add(jMenuItem_B);
        jPopupMenu.add(jMenuItem_C);
        jMenuItem_A.addActionListener(menuActionListener);
        jMenuItem_B.addActionListener(menuActionListener);
        jMenuItem_C.addActionListener(menuActionListener);

        addMouseListener(myMouseAdapter);
    }

    MouseAdapter myMouseAdapter = new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            if (e.isPopupTrigger()) {
                jPopupMenu.show(e.getComponent(), e.getX(), e.getY());
            }
        }
        
        @Override
        public void mouseReleased(MouseEvent e) {
            if (e.isPopupTrigger()) {
                jPopupMenu.show(e.getComponent(), e.getX(), e.getY());
            }
        }

    };
    
    ActionListener menuActionListener = new ActionListener(){
 
        @Override
        public void actionPerformed(ActionEvent e) {
            jLabel.setText(e.getActionCommand());
        }
         
    };

    private static void createAndShowGUI() {
        JavaMenu myFrame = new JavaMenu();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setSize(400, 300);
        myFrame.prepareUI();
        myFrame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

}

Tuesday, January 7, 2014

Add ActionListener to JMenuItem, JCheckBoxMenuItem and JRadioButtonMenuItem

This example add ActionListener to JMenuItem, JCheckBoxMenuItem and JRadioButtonMenuItem:
Add ActionListener to JMenuItem, JCheckBoxMenuItem and JRadioButtonMenuItem
Add ActionListener to JMenuItem, JCheckBoxMenuItem and JRadioButtonMenuItem

package javamenu;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMenu extends JFrame {
    
    JLabel jLabel;

    private void prepareUI() {
        
        jLabel = new JLabel("Label", JLabel.RIGHT);
        getContentPane().add(jLabel);
        
        JMenuBar jMenuBar = new JMenuBar();

        JMenu menuFile = new JMenu("File");
        menuFile.setMnemonic(KeyEvent.VK_F);
        jMenuBar.add(menuFile);
        JMenu menuOption = new JMenu("Options");
        menuOption.setMnemonic(KeyEvent.VK_P);
        jMenuBar.add(menuOption);

        //MenuItem New, Open, Save under File
        JMenuItem menuItemNew = new JMenuItem("New", KeyEvent.VK_N);
        menuFile.add(menuItemNew);
        JMenuItem menuItemOpen = new JMenuItem("Open", KeyEvent.VK_O);
        menuFile.add(menuItemOpen);
        JMenuItem menuItemSave = new JMenuItem("Save", KeyEvent.VK_S);
        menuFile.add(menuItemSave);

        //CheckBox A, B, C under Options
        JCheckBoxMenuItem jCheckBoxMenuItem_A = new JCheckBoxMenuItem("Check A");
        jCheckBoxMenuItem_A.setMnemonic(KeyEvent.VK_A);
        menuOption.add(jCheckBoxMenuItem_A);
        
        JCheckBoxMenuItem jCheckBoxMenuItem_B = new JCheckBoxMenuItem("Check B");
        jCheckBoxMenuItem_B.setMnemonic(KeyEvent.VK_B);
        menuOption.add(jCheckBoxMenuItem_B);
        
        JCheckBoxMenuItem jCheckBoxMenuItem_C = new JCheckBoxMenuItem("Check C");
        jCheckBoxMenuItem_C.setMnemonic(KeyEvent.VK_C);
        menuOption.add(jCheckBoxMenuItem_C);
        menuOption.addSeparator();
        
        //Create ButtonGroup for radio button D, E, F
        ButtonGroup buttonGroup = new ButtonGroup();
        
        JRadioButtonMenuItem jRadioButtonMenuItem_D = new JRadioButtonMenuItem("Option D", true);
        jRadioButtonMenuItem_D.setMnemonic(KeyEvent.VK_D);
        menuOption.add(jRadioButtonMenuItem_D);
        buttonGroup.add(jRadioButtonMenuItem_D);

        JRadioButtonMenuItem jRadioButtonMenuItem_E = new JRadioButtonMenuItem("Option E");
        jRadioButtonMenuItem_E.setMnemonic(KeyEvent.VK_E);
        menuOption.add(jRadioButtonMenuItem_E);
        buttonGroup.add(jRadioButtonMenuItem_E);
        
        JRadioButtonMenuItem jRadioButtonMenuItem_F = new JRadioButtonMenuItem("Option F");
        jRadioButtonMenuItem_F.setMnemonic(KeyEvent.VK_F);
        menuOption.add(jRadioButtonMenuItem_F);
        buttonGroup.add(jRadioButtonMenuItem_F);
        
        setJMenuBar(jMenuBar);
       
        //Add ActionListener
        menuItemNew.addActionListener(menuActionListener);
        menuItemOpen.addActionListener(menuActionListener);
        menuItemSave.addActionListener(menuActionListener);
        jCheckBoxMenuItem_A.addActionListener(menuActionListener);
        jCheckBoxMenuItem_B.addActionListener(menuActionListener);
        jCheckBoxMenuItem_C.addActionListener(menuActionListener);
        jRadioButtonMenuItem_D.addActionListener(menuActionListener);
        jRadioButtonMenuItem_E.addActionListener(menuActionListener);
        jRadioButtonMenuItem_F.addActionListener(menuActionListener);
    }

    ActionListener menuActionListener = new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent e) {
            jLabel.setText(e.getActionCommand());
        }
        
    };

    private static void createAndShowGUI() {
        JavaMenu myFrame = new JavaMenu();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setSize(400, 300);
        myFrame.prepareUI();
        myFrame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

}

Monday, January 6, 2014

Java JMenu Example

Example of using JMenuBar, JMenu, JMenuItem, JCheckBoxMenuItem, JRadioButtonMenuItem and ButtonGroup.
Example of Java JMenu
Example of Java JMenu

package javamenu;

import java.awt.event.KeyEvent;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingUtilities;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaMenu extends JFrame {

    private void prepareUI() {
        JMenuBar jMenuBar = new JMenuBar();

        JMenu menuFile = new JMenu("File");
        menuFile.setMnemonic(KeyEvent.VK_F);
        jMenuBar.add(menuFile);
        JMenu menuOption = new JMenu("Options");
        menuOption.setMnemonic(KeyEvent.VK_P);
        jMenuBar.add(menuOption);

        //MenuItem New, Open, Save under File
        JMenuItem menuItemNew = new JMenuItem("New", KeyEvent.VK_N);
        menuFile.add(menuItemNew);
        JMenuItem menuItemOpen = new JMenuItem("Open", KeyEvent.VK_O);
        menuFile.add(menuItemOpen);
        JMenuItem menuItemSave = new JMenuItem("Save", KeyEvent.VK_S);
        menuFile.add(menuItemSave);

        //CheckBox A, B, C under Options
        JCheckBoxMenuItem jCheckBoxMenuItem_A = new JCheckBoxMenuItem("Check A");
        jCheckBoxMenuItem_A.setMnemonic(KeyEvent.VK_A);
        menuOption.add(jCheckBoxMenuItem_A);
        
        JCheckBoxMenuItem jCheckBoxMenuItem_B = new JCheckBoxMenuItem("Check B");
        jCheckBoxMenuItem_B.setMnemonic(KeyEvent.VK_B);
        menuOption.add(jCheckBoxMenuItem_B);
        
        JCheckBoxMenuItem jCheckBoxMenuItem_C = new JCheckBoxMenuItem("Check C");
        jCheckBoxMenuItem_C.setMnemonic(KeyEvent.VK_C);
        menuOption.add(jCheckBoxMenuItem_C);
        menuOption.addSeparator();
        
        //Create ButtonGroup for radio button D, E, F
        ButtonGroup buttonGroup = new ButtonGroup();
        
        JRadioButtonMenuItem jRadioButtonMenuItem_D = new JRadioButtonMenuItem("Option D", true);
        jRadioButtonMenuItem_D.setMnemonic(KeyEvent.VK_D);
        menuOption.add(jRadioButtonMenuItem_D);
        buttonGroup.add(jRadioButtonMenuItem_D);

        JRadioButtonMenuItem jRadioButtonMenuItem_E = new JRadioButtonMenuItem("Option E");
        jRadioButtonMenuItem_E.setMnemonic(KeyEvent.VK_E);
        menuOption.add(jRadioButtonMenuItem_E);
        buttonGroup.add(jRadioButtonMenuItem_E);
        
        JRadioButtonMenuItem jRadioButtonMenuItem_F = new JRadioButtonMenuItem("Option F");
        jRadioButtonMenuItem_F.setMnemonic(KeyEvent.VK_F);
        menuOption.add(jRadioButtonMenuItem_F);
        buttonGroup.add(jRadioButtonMenuItem_F);
        
        setJMenuBar(jMenuBar);
    }

    private static void createAndShowGUI() {
        JavaMenu myFrame = new JavaMenu();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setSize(400, 300);
        myFrame.prepareUI();
        myFrame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            createAndShowGUI();
        });
    }

}



Next:
- Add ActionListener to JMenuItem, JCheckBoxMenuItem and JRadioButtonMenuItem