Sunday, January 26, 2014

Example of String.trim()

String.trim() returns a copy of the string, with leading and trailing whitespace omitted.

package javaextrimstring;

public class JavaExTrimString {

    public static void main(String[] args) {
        doTrim("abc def");
        doTrim(" abc def ");
        doTrim("   abc def");
        doTrim(" _ abc def");
    }
    
    static private void doTrim(String s){
        System.out.println(s + " => " + s.trim());
    }
}

Example of String.trim()
Example of String.trim()

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

Friday, January 24, 2014

Convert between String and char array

Convert between String and char array
Convert between String and char array

package javastringtochararray;

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

    public static void main(String[] args) {
        String src = "Hello Java-buddy";
        char[] array;
        
        //convert String to char array
        array = src.toCharArray();
        for(int c = 0; c<array.length; c++){
            System.out.print(array[c]);
        }
        System.out.println();
        
        //convert char array to String
        String newString = new String(array);
        System.out.println(newString);
        
        System.out.println("src.equals(newString) = " + src.equals(newString));
    }
    
}

Thursday, January 23, 2014

Java Programming: Learn Advanced Skills from a Java Expert (Oracle Press)

Java Programming (Oracle Press)



Develop, Compile, and Debug High-Performance Java Applications

Take your Java skills to the next level using the expert programming techniques contained in this Oracle Press guide. Featuring real-world code samples and detailed instructions, Java Programming demonstrates how to fully utilize the powerful features of Java SE 7. Find out how to design multithreaded and network applications, integrate structured exception handling, use Java libraries, and develop Swing-based GUIs and applets. Inheritance, generics, and utility classes are are covered in this practical resource.


  • Create custom classes, methods, arrays, and operators
  • Control program flow using conditional statements
  • Handle multithreaded, network, and I/O programming
  • Learn new constructs in multithreading
  • Incorporate enums, annotations, and autoboxing
  • Recover from errors, input failures, and exceptions
  • Use Java Swing to build lightweight GUIs and applets
  • Cut development time using the collections framework
  • Work with the latest Java libraries and utility classes


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

Friday, January 17, 2014

Get maximum day of month of leap year

This example show how to get maximum day of month of leap year, using getActualMaximum().

Get maximum day of month of leap year
Get maximum day of month of leap year

package javacalendar_leapyear;

import java.util.Calendar;
import java.util.GregorianCalendar;

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

    public static void main(String[] args) {
        Calendar cal1 = new GregorianCalendar(2014, Calendar.FEBRUARY, 1);
        int days1a = cal1.getActualMaximum(Calendar.DAY_OF_MONTH);
        int days1b = cal1.getMaximum(Calendar.DAY_OF_MONTH);

        Calendar cal2 = new GregorianCalendar(2016, Calendar.FEBRUARY, 1);
        int days2a = cal2.getActualMaximum(Calendar.DAY_OF_MONTH);
        int days2b = cal2.getMaximum(Calendar.DAY_OF_MONTH);
        
        System.out.println("2014 FEBRUARY ActualMaximum DAY_OF_MONTH: " + days1a);
        System.out.println("2014 FEBRUARY Maximum DAY_OF_MONTH: " + days1b);
        System.out.println("2016 FEBRUARY ActualMaximum DAY_OF_MONTH: " + days2a);
        System.out.println("2016 FEBRUARY Maximum DAY_OF_MONTH: " + days2b);
    }
    
}

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

JavaFX Everywhere: a application running on Desktop, iOS, Android and Raspberry Pi

This video shows a JavaFX demo application running on Desktop, iOS, Android and Raspberry Pi.

Java exercise: Display JTable data in line chart using JComponent

It's a simple example to display data in JTable in a line-chart, by combining example of "JTable" and "JComponent". To make it simple, only the first row will be shown on chart.

Display JTable data in line chart
Display JTable data in line chart

package javamyframe;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Label;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.AbstractTableModel;

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

    Label labelInfo;
    JTable jTable;

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

    private static void createAndShowGUI() {
        JavaMyFrame myFrame = new JavaMyFrame();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.prepareUI();
        myFrame.pack();
        myFrame.setVisible(true);
    }
    
    private void prepareUI(){
        
        JPanel vPanel = new JPanel();
        vPanel.setLayout(new BoxLayout(vPanel, BoxLayout.Y_AXIS));
        
        MyChart myChart = new MyChart();
        myChart.setPreferredSize(new Dimension(450, 200));
        
        jTable = new JTable(new MyTableModel());
        jTable.getSelectionModel()
                .addListSelectionListener(new MyRowColListener());
        jTable.getColumnModel().getSelectionModel()
                .addListSelectionListener(new MyRowColListener());

        jTable.setFillsViewportHeight(true);
        JScrollPane jScrollPane = new JScrollPane(jTable);
        jScrollPane.setPreferredSize(new Dimension(450, 100));
        vPanel.add(jScrollPane);

        labelInfo = new Label();
        vPanel.add(labelInfo);
        
        Button buttonPrintAll = new Button("Print All");
        buttonPrintAll.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println();
                for(int i=0; i<jTable.getRowCount(); i++){
                    for(int j=0; j<jTable.getColumnCount(); j++){
                        String val = String.valueOf(jTable.getValueAt(i, j));
                        System.out.print(val + "\t");
                    }
                    System.out.println();
                }
                
                //Create ListArray for the first row
                //and update MyChart
                ArrayList<Integer> l = new ArrayList<>();
                for(int i=0; i<jTable.getColumnCount(); i++){
                    l.add((Integer)jTable.getValueAt(0, i));
                }
                myChart.updateList(l);
            }
        });
        
        getContentPane().add(myChart, BorderLayout.PAGE_START);
        getContentPane().add(vPanel, BorderLayout.CENTER);
        getContentPane().add(buttonPrintAll, BorderLayout.PAGE_END);
    }
    
    private class MyChart extends JComponent {
        ArrayList<Integer> chartList;
        
        public void updateList(ArrayList<Integer> l){
            System.out.println("updateList()");
            
            chartList = l;
            repaint();
        }

        @Override
        public void paint(Graphics g) {
            System.out.println("paint()");
            
            if(chartList != null){
                paintMe(g);
            }
        }
        
        private void paintMe(Graphics g){
            Graphics2D graphics2d = (Graphics2D)g;
            graphics2d.setColor(Color.blue);
            
            int width = getWidth();
            int height = getHeight();
            
            float hDiv = (float)width/(float)(chartList.size()-1);
            float vDiv = (float)height/(float)(Collections.max(chartList));
            
            for(int i=0; i<chartList.size()-1; i++){
                
                int value1, value2;
                if(chartList.get(i)==null){
                    value1 = 0;
                }else{
                    value1 = chartList.get(i);
                }
                if(chartList.get(i+1)==null){
                    value2 = 0;
                }else{
                    value2 = chartList.get(i+1);
                }
                
                graphics2d.drawLine(
                        (int)(i*hDiv), 
                        height - ((int)(value1*vDiv)),
                        (int)((i+1)*hDiv), 
                        height - ((int)(value2*vDiv)));
            }
            
            graphics2d.drawRect(0, 0, width, height);
        }
        
    }
    
    private class MyRowColListener implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            System.out.println("valueChanged: " + e.toString());

            if (!e.getValueIsAdjusting()) {
                
                int row = jTable.getSelectedRow();
                int col = jTable.getSelectedColumn();
                
                if(row>= 0 && col>=0){
                    int selectedItem = (int)jTable.getValueAt(row, col);
                    labelInfo.setText("MyRowListener: " 
                        + row + " : " + col + " = " + selectedItem);
                }
                
            }
        }
    }
    
    class MyTableModel extends AbstractTableModel {
        private String[] DayOfWeek = {
            "Monday",
            "Tuesday",
            "Wednesday",
            "Thursday",
            "Friday",
            "Saturday",
            "Sunday"};
    
        private Object[][] tableData = {
            {1, 2, 3, 4, 5, 6, 7},
            {4, 3, 2, 1, 7, 6, 5},
            {12, 20, 13, 14, 11, 24, 56},
            {13, 29, 23, 24, 25, 21, 20},
            {2, 4, 6, 8, 10, 12, 14},
            {11, 21, 33, 4, 9, 5, 4}};

        @Override
        public int getColumnCount() {
            return DayOfWeek.length;
        }

        @Override
        public int getRowCount() {
            return tableData.length;
        }

        @Override
        public String getColumnName(int col) {
            return DayOfWeek[col];
        }

        @Override
        public Object getValueAt(int row, int col) {
            return tableData[row][col];
        }

        @Override
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            return true;
        }

        @Override
        public void setValueAt(Object value, int row, int col) {
            tableData[row][col] = value;
            fireTableCellUpdated(row, col);
        }

    }
}

Saturday, January 4, 2014

Detect mousePressed and mouseDragged with MouseAdapter

This example implement MouseAdpater to act as both MouseListener and MouseMotionListener, to handle mousePressed and mouseDragged to draw Oval on JComponent dynamically.

Detect mousePressed and mouseDragged with MouseAdapter
Detect mousePressed and mouseDragged with MouseAdapter

package javaswingdrawing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaSwingDrawing extends JComponent {
    
    int mouseX, mouseY;
    int mouseX_dragged, mouseY_dragged;
    boolean mouseDragged;

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

    public JavaSwingDrawing() {
        addMouseListener(myMouseAdapter);
        addMouseMotionListener(myMouseAdapter);
    }
    
    MouseAdapter myMouseAdapter = new MouseAdapter(){

        @Override
        public void mousePressed(MouseEvent e) {
            mouseX = e.getX();
            mouseY = e.getY();
            mouseDragged = false;
            repaint();
        }

        @Override
        public void mouseDragged(MouseEvent e) {
            mouseX_dragged = e.getX();
            mouseY_dragged = e.getY();
            mouseDragged = true;
            repaint();
        }

    };

    @Override
    public void paint(Graphics g) {
        
        Graphics2D graphics2d = (Graphics2D)g;
        graphics2d.setColor(Color.blue);
        if(mouseDragged){
            int x, y;
            int w, h;
            
            if(mouseX > mouseX_dragged){
                x = mouseX_dragged;
                w = mouseX - mouseX_dragged;
            }else{
                x = mouseX;
                w = mouseX_dragged - mouseX;
            }
            
            if(mouseY > mouseY_dragged){
                y = mouseY_dragged;
                h = mouseY - mouseY_dragged;
            }else{
                y = mouseY;
                h = mouseY_dragged - mouseY;
            }
            
            graphics2d.drawOval(x, y, w, h);
        }else{
            graphics2d.fillOval(mouseX-5, mouseY-5, 10, 10);
        }
    }

    private static void createAndShowGUI() {
        JFrame myFrame = new JFrame();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setSize(new Dimension(400, 300));
        myFrame.setLayout(new BorderLayout());
        myFrame.add(new JavaSwingDrawing(), BorderLayout.CENTER);
        myFrame.setVisible(true);
    }
}

Friday, January 3, 2014

Implement MouseAdapter for JComponent

Implement MouseAdapter for JComponent
Implement MouseAdapter for JComponent

package javaswingdrawing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * @web http://java-buddy.blogspot.com/
 */
public class JavaSwingDrawing extends JComponent {
    
    int mouseX, mouseY;

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

    public JavaSwingDrawing() {
        addMouseListener(myMouseAdapter);
    }
    
    MouseAdapter myMouseAdapter = new MouseAdapter(){

        @Override
        public void mousePressed(MouseEvent e) {
            mouseX = e.getX();
            mouseY = e.getY();
            repaint();
        }

    };

    @Override
    public void paint(Graphics g) {
        
        Graphics2D graphics2d = (Graphics2D)g;
        graphics2d.setColor(Color.blue);
        graphics2d.fillOval(mouseX-5, mouseY-5, 10, 10);
    }

    private static void createAndShowGUI() {
        JFrame myFrame = new JFrame();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setSize(new Dimension(400, 300));
        myFrame.setLayout(new BorderLayout());
        myFrame.add(new JavaSwingDrawing(), BorderLayout.CENTER);
        myFrame.setVisible(true);
    }
}



Next: Detect mousePressed and mouseDragged with MouseAdapter

Example of drawing something on Swing JComponent

Draw something on Swing JComponent
Draw something on Swing JComponent

package javaswingdrawing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

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

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

    @Override
    public void paint(Graphics g) {
        
        Graphics2D graphics2d = (Graphics2D)g;
        
        int w = getWidth();
        int h = getHeight();
        graphics2d.setColor(Color.red);
        graphics2d.fillOval(w/4, h/4, w/2, h/2);
        graphics2d.setColor(Color.blue);
        graphics2d.fillRect(w/2, h/2, w/4, h/4);
    }

    private static void createAndShowGUI() {
        JFrame myFrame = new JFrame();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setSize(new Dimension(400, 300));
        myFrame.setLayout(new BorderLayout());
        myFrame.add(new JavaSwingDrawing(), BorderLayout.CENTER);
        myFrame.setVisible(true);
    }
}


Next:
- Implement MouseAdapter for JComponent
- Detect mousePressed and mouseDragged with MouseAdapter

More:
- Display JTable data in line chart using JComponent

Thursday, January 2, 2014

Draw something on JFrame


package javaswingdrawing;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

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

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

    @Override
    public void paint(Graphics g) {
        int w = getWidth();
        int h = getHeight();
        g.setColor(Color.red);
        g.fillOval(w/4, h/4, w/2, h/2);
        g.setColor(Color.blue);
        g.fillRect(w/2, h/2, w/4, h/4);
        //super.paint(g);
    }

    private static void createAndShowGUI() {
        JavaSwingDrawing myFrame = new JavaSwingDrawing();
        myFrame.setTitle("java-buddy.blogspot.com");
        myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        myFrame.setPreferredSize(new Dimension(400, 300));

        myFrame.pack();
        myFrame.setVisible(true);
    }
}