Thursday, September 27, 2012

SwingWorker

javax.swing.SwingWorker is an abstract class to perform lengthy GUI-interaction tasks in a background thread. It's a working example to use javax.swing.SwingWorker.

SwingWorker Example


package javatesttimer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaTestTimer {
    
    static int counter = 0;
    static JFrameWin jFrameWindow;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(runJFrameLater);
    }
   
    static Runnable runJFrameLater = new Runnable() {
        
        @Override
        public void run() {
            jFrameWindow = new JFrameWin();
            jFrameWindow.setVisible(true);
        }
     
    };
    
    public static class JFrameWin extends JFrame{
        
        JLabel label;
        
        public JFrameWin(){
            this.setTitle("java-buddy.blogspot.com");
            this.setSize(300, 200);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            label = new JLabel();
            label.setText("un-initialized!");
            
            JButton buttonStart = new JButton("Start SwingWorker");
            buttonStart.addActionListener(new ActionListener(){

                @Override
                public void actionPerformed(ActionEvent e) {
                    new MySwingWorker(label).execute();
                }
            });
            
            Box verticalBox = Box.createVerticalBox();
            
            verticalBox.add(buttonStart);
            verticalBox.add(label);
            this.add(verticalBox);
        }
        
        public void setLabel(String l){
            label.setText(l);
        }
    }
    
    public static class MySwingWorker extends SwingWorker<String, Integer>{
        
        private JLabel workerLabel;

        //Constructor
        public MySwingWorker(JLabel workerLabel) {
            this.workerLabel = workerLabel;
        }

        //in background thread
        @Override
        protected String doInBackground() throws Exception {
            
            for(int i = 0; i < 10; i++){
                publish(i);
                Thread.sleep(1000); //Perform long-time job
            }
            return "DONE";
        }

        //in EDT
        @Override
        protected void process(List<Integer> chunks) {
            for(Integer chunk : chunks){
                workerLabel.setText(String.valueOf(chunk));
            }
        }

        //in EDT
        @Override
        protected void done() {
            try {
                workerLabel.setText(get());
            } catch (InterruptedException ex) {
                Logger.getLogger(JavaTestTimer.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ExecutionException ex) {
                Logger.getLogger(JavaTestTimer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
    }
}


Related:
- javax.swing.Timer and java.util.Timer

Wednesday, September 26, 2012

SwingUtilities.isEventDispatchThread(), determine if the current thread is an AWT event dispatching thread.

Last post describe about javax.swing.Timer and java.util.Timer, Java API provide a SwingUtilities.isEventDispatchThread() method to determine if the current thread is an AWT event dispatching thread.

The last exercise is modified to using the method SwingUtilities.isEventDispatchThread() to determine if it's need to create another Runnable or not.

SwingUtilities.isEventDispatchThread(), determine if the current thread is an AWT event dispatching thread.


package javatesttimer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaTestTimer {
    
    static int counter = 0;
    static JFrameWin jFrameWindow;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(runJFrameLater);
    }
    
    //if it's in Event Dispatch Thread, setLabel() directly.
    //Otherwise, create a Runnable and invoke later to call setLabel() in EDT.
    private static void setLabelAtEDT(final int c){
        
        if(SwingUtilities.isEventDispatchThread()){
            jFrameWindow.setLabel("Directly: " 
                                + String.valueOf(c));
        }else{
            SwingUtilities.invokeLater(
                                new Runnable(){
                                    
                                    @Override
                                    public void run() {
                                        jFrameWindow.setLabel("invokeLater: " 
                                                + String.valueOf(c));
                                        counter++;
                                    }
                                }
                        );
        }
        
    }
    
    //Create Timer of javax.swing.Timer
    private static void testSwingTimer(){
        javax.swing.Timer swingTimer = new javax.swing.Timer(
                5000,
                new ActionListener(){
                    
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        setLabelAtEDT(counter);
                        counter++;
                    }
        });
        
        swingTimer.start();
    }
    
    //Create Timer of java.util.Timer
    private static void testUtilTimer(){
        java.util.Timer utilTimer = new java.util.Timer();
        
        utilTimer.schedule(
                new TimerTask(){
                    
                    @Override
                    public void run() {
                        setLabelAtEDT(counter);
                    }
                
                }, 
                0, 
                5000);
    }
    
    static Runnable runJFrameLater = new Runnable() {
        
        @Override
        public void run() {
            jFrameWindow = new JFrameWin();
            jFrameWindow.setVisible(true);
            
            //testSwingTimer();
            testUtilTimer();
        }
     
    };
    
    public static class JFrameWin extends JFrame{
        
        JLabel label;
        
        public JFrameWin(){
            this.setTitle("java-buddy.blogspot.com");
            this.setSize(300, 200);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            label = new JLabel();
            label.setText("un-initialized!");
            
            this.add(label);
        }
        
        public void setLabel(String l){
            label.setText(l);
        }
    }
}


javax.swing.Timer and java.util.Timer

Java SE provide javax.swing.Timer and java.util.Timer to schedule tasks to be executed at regular time intervals. Here is a example demonstrate how to create javax.swing.Timer and java.util.Timer.

javax.swing.Timer and java.util.Timer


It can be notice that the actionPerformed() of javax.swing.Timer will be run on EDT(Event Dispatching Thread), such that it can set UI components directly. On the other hand, the TimerTask of java.util.Timer will be run on NON-EDT, it cannot set UI directly. Such that we have to create and invoke another Runnable object later in EDT to set UI components.

The event dispatching thread (EDT) is a background thread used in Java to process events from the Abstract Window Toolkit (AWT) graphical user interface event queue. These events are primarily update events that cause user interface components to redraw themselves, or input events from input devices such as the mouse or keyboard. The AWT uses a single-threaded painting model in which all screen updates must be performed from a single thread. The event dispatching thread is the only valid thread to update the visual state of visible user interface components. Updating visible components from other threads is the source of many common bugs in Java programs that use Swing. ~ Source: Event dispatching thread from Wikipedia.

So, if you want to schedule a task to perform something related to UI, you should use javax.swing.Timer. Otherwise, you can use java.util.Timer.

Example code:
package javatesttimer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaTestTimer {
    
    static int counter = 0;
    static JFrameWin jFrameWindow;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(runJFrameLater);
    }
    
    //Create Timer of javax.swing.Timer
    private static void testSwingTimer(){
        javax.swing.Timer swingTimer = new javax.swing.Timer(
                5000,
                new ActionListener(){
                    
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        jFrameWindow.setLabel("testSwingTimer: " 
                                + String.valueOf(counter));
                        counter++;
                    }
        });
        
        swingTimer.start();
    }
    
    //Create Timer of java.util.Timer
    private static void testUtilTimer(){
        java.util.Timer utilTimer = new java.util.Timer();
        
        utilTimer.schedule(
                new TimerTask(){
                    
                    @Override
                    public void run() {
                        SwingUtilities.invokeLater(
                                new Runnable(){
                                    
                                    @Override
                                    public void run() {
                                        jFrameWindow.setLabel("testUtilTimer: " 
                                                + String.valueOf(counter));
                                        counter++;
                                    }
                                }
                                
                        );
                    }
                
                }, 
                0, 
                5000);
    }
    
    static Runnable runJFrameLater = new Runnable() {
        
        @Override
        public void run() {
            jFrameWindow = new JFrameWin();
            jFrameWindow.setVisible(true);
            
            testSwingTimer();
            //testUtilTimer();
        }
     
    };
    

    
    public static class JFrameWin extends JFrame{
        
        JLabel label;
        
        public JFrameWin(){
            this.setTitle("java-buddy.blogspot.com");
            this.setSize(300, 200);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            label = new JLabel();
            label.setText("un-initialized!");
            
            this.add(label);

        }
        
        public void setLabel(String l){
            label.setText(l);
        }
    }
}


Related:
- SwingUtilities.isEventDispatchThread(), determine if the current thread is an AWT event dispatching thread.
- javax.swing.SwingWorker


Monday, September 24, 2012

Ensemble: over 100 JavaFX sample application

Ensemble provides a gallery of over 100 sample applications that use a wide range of JavaFX features, such as graphics, UI controls, animation, charts, media and WebView. Source code for each sample and links to API documentation are also provided. Ensemble will provide developers with an interactive reference tool for what they can build with JavaFX.

Ensemble


Launch Ensemble

Tuesday, September 18, 2012

Oracle Certified Associate, Java SE 7 Programmer Study Guide



Each objective is addressed using a series of programming examples. When the topic impacts memory, stack and heap illustrations are used to provide the reader with a more in depth understanding of the topic. At the end of each chapter, a series of sample questions are provided to reinforce your knowledge. This book is designed to help you prepare for the Oracle Certified Associate, Java SE 7 Programmer Certification exam (1Z0-803) and gain confidence in your understanding and use of Java. Basic knowledge of Java programming is expected.

Monday, September 17, 2012

j2objc - A Java to iOS Objective-C translation tool and runtime



J2ObjC is an open-source command-line tool from Google that translates Java code to Objective-C for the iOS (iPhone/iPad) platform. This tool enables Java code to be part of an iOS application's build, as no editing of the generated files is necessary. The goal is to write an app's non-UI code (such as data access, or application logic) in Java, which is then shared by web apps (using GWT), Android apps, and iOS apps.

J2ObjC supports most Java language and runtime features required by client-side application developers, including exceptions, inner and anonymous classes, generic types, threads and reflection. JUnit test translation and execution is also supported.

J2ObjC is currently between alpha and beta quality. Several Google projects rely on it, but when new projects first start working with it, they usually find new bugs to be fixed. Apparently every Java developer has a slightly different way of using Java, and the tool hasn't translated all possible paths yet. It's initial version number is 0.5, which hopefully represents its release status correctly.

Project Home: http://code.google.com/p/j2objc/

Monday, September 10, 2012

Nested JSplitPane

Example of Nested JSplitPane:

Nested JSplitPane


package javatestsplitpane;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(runJSplitPaneLater);
    }
    
    static Runnable runJSplitPaneLater = new Runnable(){

        @Override
        public void run() {
            MyJFrameWin myJFrameWin = new MyJFrameWin();
            myJFrameWin.setVisible(true);
        }
        
    };
    
    public static class MyJFrameWin extends JFrame{
        
        JSplitPane jSplitPane, jSplitPane2;
        JPanel jPanel1, jPanel2a, jPanel2b;
        
        public MyJFrameWin(){
            this.setTitle("java-buddy.blogspot.com");
            this.setSize(400, 300);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            jPanel1 = new JPanel();
            jPanel2a = new JPanel();
            jPanel2b = new JPanel();
            
            jSplitPane2 = new JSplitPane(JSplitPane.VERTICAL_SPLIT, 
                    jPanel2a, jPanel2b);
            jSplitPane2.setOneTouchExpandable(true);
            jSplitPane2.setDividerLocation(100);
            
            jSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, 
                    jPanel1, jSplitPane2);
            jSplitPane.setOneTouchExpandable(true);
            jSplitPane.setDividerLocation(150);
            
            getContentPane().add(jSplitPane);
        }
    }
}


Friday, September 7, 2012

Java for OS X Lion 2012-005 Released

Apple have released Java for OS X Lion 2012-005 (along with the corresponding Java for Mac OS X 10.6 Update 10).

This update includes security fixes to align it with Oracle’s Java SE 6 Update 35.

The update will come through the software updater or can be downloaded from the Apple downloads page.


DrJava: a lightweight development environment for writing Java programs



DrJava is a lightweight development environment for writing Java programs. It is designed primarily for students, providing an intuitive interface and the ability to interactively evaluate Java code. It also includes powerful features for more advanced users. DrJava is available for free under the BSD License, and it is under active development by the JavaPLT group at Rice University.

Website: http://drjava.sourceforge.net/

Basic JSplitPane

JSplitPane is used to divide two (and only two) Components. The two Components are graphically divided based on the look and feel implementation, and the two Components can then be interactively resized by the user.

Basic JSplitPane


package javatestsplitpane;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.SwingUtilities;

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

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(runJSplitPaneLater);
    }
    
    static Runnable runJSplitPaneLater = new Runnable(){

        @Override
        public void run() {
            MyJFrameWin myJFrameWin = new MyJFrameWin();
            myJFrameWin.setVisible(true);
        }
        
    };
    
    public static class MyJFrameWin extends JFrame{
        
        JSplitPane jSplitPane;
        JPanel jPanel1, jPanel2;
        
        public MyJFrameWin(){
            this.setTitle("java-buddy.blogspot.com");
            this.setSize(400, 300);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            jPanel1 = new JPanel();
            jPanel2 = new JPanel();
            
            jSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, 
                    jPanel1, jPanel2);
            jSplitPane.setOneTouchExpandable(true);
            jSplitPane.setDividerLocation(150);
            
            getContentPane().add(jSplitPane);
        }
    }
}


Next:
- Nested JSplitPane


Wednesday, September 5, 2012

55 New Things in Java 7 - GUI


Part of an ongoing series of 55 new things in Java 7. This edition features 8 GUI changes that were part of Java 7

Border examples of created by BorderFactory

It's more border examples of created by BorderFactory.

Border examples of created by BorderFactory


package javatestswing;

import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;

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

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

        @Override
        public void run() {
            MyJFrameWin myjFrameWindow;
            myjFrameWindow = new MyJFrameWin();
            myjFrameWindow.setVisible(true);
        }
    
    };
    
    public static class MyJFrameWin extends JFrame{
        
        public MyJFrameWin(){
            this.setTitle("java-buddy.blogspot.com");
            this.setSize(350, 450);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            this.setLayout(new FlowLayout());
            
            this.add(createBorderedPanel(BorderFactory.createRaisedBevelBorder(), 
                    "createRaisedBevelBorder()"));
            
            this.add(createBorderedPanel(BorderFactory.createBevelBorder(BevelBorder.LOWERED),
                    "createBevelBorder(BevelBorder.LOWERED)"));
            
            this.add(createBorderedPanel(BorderFactory.createBevelBorder(BevelBorder.RAISED),
                    "createBevelBorder(BevelBorder.RAISED)"));
            
            this.add(createBorderedPanel(BorderFactory.createCompoundBorder(
                    BorderFactory.createBevelBorder(BevelBorder.RAISED), 
                    BorderFactory.createBevelBorder(BevelBorder.LOWERED)),
                    "createCompoundBorder(..RAISED, ..LOWERED)"));
            
            this.add(createBorderedPanel(BorderFactory.createEtchedBorder(), 
                    "createEtchedBorder()"));
            
            this.add(createBorderedPanel(
                    BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), 
                    "createEtchedBorder(EtchedBorder.LOWERED)"));
            
            this.add(createBorderedPanel(
                    BorderFactory.createEtchedBorder(EtchedBorder.RAISED), 
                    "createEtchedBorder(EtchedBorder.RAISED)"));
            
            this.add(createBorderedPanel(
                    BorderFactory.createEtchedBorder(
                        Color.lightGray, 
                        Color.yellow), 
                    "createEtchedBorder(Color.lightGray, Color.yellow)"));
            
            this.add(createBorderedPanel(
                    BorderFactory.createLineBorder(Color.red), 
                    "createLineBorder(Color.red)"));
            
            this.add(createBorderedPanel(
                    BorderFactory.createLineBorder(Color.blue, 5), 
                    "createLineBorder(Color.blue, 5)"));

            this.add(createBorderedPanel(BorderFactory.createDashedBorder(null), 
                    "createDashedBorder(null)"));
            
        }
    }
    
    private static JPanel createBorderedPanel(Border b, String name){
        JLabel label = new JLabel(name);
        
        JPanel panel = new JPanel();
        panel.setBorder(b);
        panel.add(label);
        
        return panel;
    }
}


Tuesday, September 4, 2012

Create border using BorderFactory

Example to create RaisedBevelBorder using javax.swing.BorderFactory.

Create border using BorderFactory

package javatestswing;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

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

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

        @Override
        public void run() {
            MyJFrameWin myjFrameWindow;
            myjFrameWindow = new MyJFrameWin();
            myjFrameWindow.setVisible(true);
        }
    
    };
    
    public static class MyJFrameWin extends JFrame{
        
        public MyJFrameWin(){
            this.setTitle("java-buddy.blogspot.com");
            this.setSize(300, 200);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         
            JButton buttonExit = new JButton(" Exit ");
            buttonExit.addActionListener(new ActionListener(){
                
                @Override
                public void actionPerformed(ActionEvent ae) {
                    System.exit(0);
                }
            });
            
            JButton buttonWithBorder = new JButton(" Button with RaisedBevelBorder ");
            //Add JPanel with Border
            JPanel jPanel = new JPanel();
            jPanel.setBorder(BorderFactory.createRaisedBevelBorder());
            jPanel.add(buttonWithBorder);
            
            JButton buttonNormal = new JButton(" Normal Button WITHOUT Border ");
            
            this.setLayout(new FlowLayout());
            this.add(jPanel);
            this.add(buttonNormal);
            this.add(buttonExit);
        }
    }
}


More border examples of created by BorderFactory.