Showing posts with label Swing. Show all posts
Showing posts with label Swing. Show all posts
Monday, June 9, 2014
Today in this article I will show you how to create or develop a Tower of Hanoi game in Java. The Tower of Hanoi is a famous problem that is solved by recursion. It has 3 towers and the first tower contains n number of disks. A person is said to have completed or solve the problem if he is able to move all the disks to the third tower with certain constraints.
    Similarly in the game that is developed here follows the rules - 1. Only one disk can be moved at a time. 2. Cannot place a larger disk on a smaller disk. The game her when starts will start with 4 initial disks. You will have to move all the disk to 3rd tower. You can use this game and ask people to complete and win the game of Tower of Hanoi. You also have a choice to select the number of disks you want to play with. So our main objective her is that we will actually not solve the Tower of Hanoi problem, rather use it as a game and ask players of the game to solve the problem.
Tuesday, April 22, 2014
Today I am going to show you how to use the swing component - JProgressBar in your GUI application. In this article , I will also focus on how to use lambda expression in swing application. You must have seen a progress bar in many applications. It actually is used to denote graphically the amount of task or work that is completed. The basic properties are :
  • Max/Min value - A progress bar always has a maximum and a minimum value
  • Current value - This value is used to denote the current progress
The class definition of JProgressBar is
public class JProgressBar
extends JComponent
implements SwingConstants, Accessible
To know more about the JProgressBar class click here
Most often you need it while reading or writing afile. Here in our example, we will carry out a simple task where we just increase an integer value at a step of 10 and set that vakue to the progress bar. Before we assign the next value the thread sleeps for 100ms so that the progress can be viewed easily. Depending on that value a text area is updated.

The output of our demo code

Two most important things must be kept in mind whether its a simple or a complex task. In our example also we have followed that.

  • You should always carry out the task in a seperate thread. In our case generating the integer value.
  • Always update the progress bar and other swing components in event-dispatch thread only. In our case we set the progress bar value with the integer and update text area.
Also here in our code instead of creating an anonymous inner class of ActionListener and Runnable we have used Lambda Expression.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
import java.awt.*;
import javax.swing.*;

public class JProgressBar_Demo {
    //initializing components
 private JFrame frame = new JFrame("Java Swing Examples");
    private JLabel headerLabel = new JLabel("", JLabel.CENTER);
    private JPanel 
                    controlPanel = new JPanel(),
                    contentPanel = new JPanel();
    
    private JProgressBar progressBar;
    private Task task;
    private JButton startButton;
    private JTextArea outputTextArea;

    public JProgressBar_Demo(){
       buildGUI();
    }
    
    public static void main(String[] args){
     JProgressBar_Demo  swingDemo = new JProgressBar_Demo();      
     swingDemo.showDemo();
    }   
    
    private void buildGUI(){
     frame.setSize(350,400);  //stting frame size
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     setLayouts();
     //adding panels to the main panel
     contentPanel.add(headerLabel);
     contentPanel.add(controlPanel);
     frame.getContentPane().add(contentPanel);  //adding main panel to frame
     frame.setVisible(true);
    }
    //sets layout of the panels
    private void setLayouts(){
     //deliberately choosing 3 rows though have 2 components
     contentPanel.setLayout(new GridLayout(3,1));
     //to add in a directional flow
     controlPanel.setLayout(new FlowLayout());
    }
    
    public void showDemo(){
     headerLabel.setText("Component in action : JProgressBar"); 

     progressBar = new JProgressBar(0, 100);
     progressBar.setValue(0);
     progressBar.setStringPainted(true);
     startButton = new JButton("Start");

     outputTextArea = new JTextArea("",5,20);
     //adding scroller to the text-area
     JScrollPane scrollPane = new JScrollPane(outputTextArea);    
     //adding event listener
     startButton.addActionListener(
          //use of lambda expression intead new ActionListener()
       e -> {
        /* all tasks other tan component update in event listeners
           should be carried out in seperate thread */
        task = new Task();                
        task.start();
      });
     //adding components
     controlPanel.add(startButton);
     controlPanel.add(progressBar);
     controlPanel.add(scrollPane);
     frame.setVisible(true);  
    }

    //This class carries out the task when start button is clicked
    private class Task extends Thread {    
     public void run(){
      for(int i =0; i<= 100; i+=10){
       //lambda expression can use only final or pseudo-final variables
       final int progress = i;
       //update swing components in event-dispatch thread
       SwingUtilities.invokeLater(
        //lambda expression instead of new Runnable()
        () -> {
         progressBar.setValue(progress);
         outputTextArea.append(String.format("%d%% of task completed.\n", progress));
        }
       );
       try {
        Thread.sleep(100);
       } catch (InterruptedException e) {}
      }
     }
    }   
}
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Saturday, June 8, 2013
Today I will tell you how you can create shaped windows in Java. This is an extraordinary feature which was added in Java7. According to this feature you can create any shape and use that shape for your window. You can also create complex shapes and give your windows that shape. Different shapes like oval, round rectangle or complex like L-shape or I-shape. Here we will inherit the JFrame class and then add the ComponentListener to it. This is because when the window will be resized the shape will be calculated automatically. We will create a shape using Ellipse2D.Double and then call setShape() method to assign the shape to it. Below is a screenshot
An oval-shaped window as seen on Ubuntu 12.04
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------

import java.awt.Shape;
import java.awt.GridBagLayout;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentAdapter;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.SwingUtilities;
import java.awt.geom.*;

public class OvalShapedWindow extends JFrame {
    public OvalShapedWindow() {
        super("Oval Window");
        setLayout(new GridBagLayout());  //setting layout

        addComponentListener(new ComponentAdapter() {
          // If the window is resized, the shape is recalculated
          @Override
          public void componentResized(ComponentEvent e) {
            Shape winShape=new Ellipse2D.Double(0,0,getWidth(),getHeight());
            setShape(winShape);  //giving shape
          }
        });

        setUndecorated(true);  //removing title-bar
        setSize(350,250);
        setLocationRelativeTo(null);  //positioning at center
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        add(new JButton("Click Me"));  //adding Button
    }

     public static void main(String[] args) {
        // Creating UI on the event-dispatching thread
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            OvalShapedWindow sw = new OvalShapedWindow();
            sw.setVisible(true);  // Display the window
          }
        });
    }
}

--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------

Total Pageviews

Followers


Labels

Popular Posts

free counters