JGuru
Wise Old Owl
Writing great software is not that difficult!!! If you are a budding programmer then surely programming will look like daunting task!!!
Here in this tutorial I'm going to show you how easy it is to write software, once you master the basics.
The Basics are as follows:
1. Master Core Java API
2. Learn OOPS (Object Oriented Programming System
3. Learn problem solving logic - logical reasoning
4. design patterns - how to design a software program
You need atleast Java 8 or higher to run these programs. Also configure the IDE for Java 8.
You should be familiar with the new Java 8 features like lambda expressions, foreach method etc.,
Let's get started!!!
Lets look at how a program is written in Java.
The SampleApp has 5 functions or methods called open(), save(), saveAs(), print(), exit(). This called the skeleton code. You must write the skeleton code first.
You can also write the same program as follows:
This program written in Java style where you define an action for specific Components - buttons in this case.
So the objective is to understand how to write a program. You define functions or methods , more utility classes for your application.
You need icons (small images used by the programs) for almost all the programs you can download the JIDE Demo icons from here : *www.jidesoft.com/products/1.4/jide_demo.zip
Unzip the jar file to directory (search for png, gif, jpg files). You can use them for your programs!!!
These icons are needed for the programs to run!!!!
For the program to run you must create a directory called 'Icons' under the Source (src) directory and place the required icons there!!
If the icons are not found , then the program won't run!!!
the icons are loaded from the Jar file using getIcon() method.
1. Write a program to download the resource from a url and also display its progress?
The resource can be anything like a image, zip file, mp3, mp4, video etc.,
Downloader.java
ScreenShot : Imgur
Run the program , enter a url in the textfield , press the Enter key.
The program will fetch the resource from the url and display its progress.
Explanation :
How the program works:
buildLayout() - build the UI of the program
getFileName(Url url) - Gets the filename paortion of the url
performDownload() - downloads the url resource from the Web
toMB(long bytes) - converts the bytes to MB.
We implement the Runnable interface , so that this task can be performed in a separate Thread.
Any long running task must execute in a separate Thread.
we use the OutputStream class to write the data (bytes read) to the disk.
progressbar is used to display the download progress.
we use the URLConnection class to connect to a particular url and fetch it.
getContentLengthLong() returns the file size and is stored in variable fileSize.
we use the InputStream class to read data (bytes) from the url
A while loop is used to loop until bytesRead < fileSize.
byteCount - read bytes from the inputstream
bytesRead = bytesRead + byteCount.
We update the progressbar value in the loop, to show the current progress.
isStopped is a flag variable used to exit the loop under some conditions.
Like for eg ., if the url doesn't exists!!!, then fileSize returns -1.
In that case exit the loop.
Here in this tutorial I'm going to show you how easy it is to write software, once you master the basics.
The Basics are as follows:
1. Master Core Java API
2. Learn OOPS (Object Oriented Programming System
3. Learn problem solving logic - logical reasoning
4. design patterns - how to design a software program
You need atleast Java 8 or higher to run these programs. Also configure the IDE for Java 8.
You should be familiar with the new Java 8 features like lambda expressions, foreach method etc.,
Let's get started!!!
Lets look at how a program is written in Java.
Code:
import java.io.File;
public class SampleApp {
// Variables declaration goes here
private File file;
private String filename;
public SampleApp(){
}
// public methods also called functions in C/C++
//opens the file for processing
public void open(){
}
// saves the file to the disk, overwrites the current file
public void save(){
}
// saves the file with a different name or under other directory
public void saveAs(){
}
// prints the file
public void print(){
}
// exits the application
public void exit(){
}
public static void main(String[] args) {
new SampleApp();
}
}
The SampleApp has 5 functions or methods called open(), save(), saveAs(), print(), exit(). This called the skeleton code. You must write the skeleton code first.
You can also write the same program as follows:
Code:
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.io.File;
public class SampleApp {
// Variables declaration goes here
private File file;
private String filename;
public SampleApp(){
}
// AbstractAction - defines the action for a specific Component.
//This class provides default implementations for the JFC Action interface. Standard behaviors like the get and set methods for Action
// object properties (icon, text, and enabled) are defined here. The developer need only subclass this abstract class and define the
// actionPerformed method.
//opens the file for processing
class OpenAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
}
}
// saves the file to the disk, overwrites the current file
class SaveAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
}
}
// saves the file with a different name or under other directory
class SaveAsAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
}
}
// prints the file
class PrintAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
}
}
// exits the application
class ExitAction extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
}
}
public static void main(String[] args) {
new SampleApp();
}
}
This program written in Java style where you define an action for specific Components - buttons in this case.
So the objective is to understand how to write a program. You define functions or methods , more utility classes for your application.
You need icons (small images used by the programs) for almost all the programs you can download the JIDE Demo icons from here : *www.jidesoft.com/products/1.4/jide_demo.zip
Unzip the jar file to directory (search for png, gif, jpg files). You can use them for your programs!!!
These icons are needed for the programs to run!!!!
For the program to run you must create a directory called 'Icons' under the Source (src) directory and place the required icons there!!
If the icons are not found , then the program won't run!!!
the icons are loaded from the Jar file using getIcon() method.
1. Write a program to download the resource from a url and also display its progress?
The resource can be anything like a image, zip file, mp3, mp4, video etc.,
Downloader.java
Code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.*;
import java.net.*;
import javax.swing.*;
// The signed long has a minimum value of -2^63 and a maximum value of 2^63-1.
// Bug fixed : changed the fileSize bytesRead from int to long!!!
/* Sample urls to download!!!
*download.netbeans.org/netbeans/8.2/final/bundles/netbeans-8.2-linux.sh
*ftp.kaist.ac.kr/eclipse/technology/epp/downloads/release/neon/2/eclipse-java-neon-2-win32.zip
*download-cf.jetbrains.com/idea/ideaIC-2018.1.1.tar.gz
*/
class Downloader extends JFrame implements Runnable {
private URL downloadURL;
private InputStream inputStream;
private OutputStream outputStream;
private byte[] buffer;
private long fileSize = 0;
private long bytesRead;
private JTextField urlTextField;
private JLabel sizeLabel;
private JLabel completeLabel;
private JProgressBar progressBar;
private final static int BUFFER_SIZE = 1024;
private boolean isStopped = false;
private Thread thread;
private final Font font = new Font("Serif", Font.PLAIN, 12);
private Downloader() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ignored) {
// Do nothing
}
thread = new Thread(this);
buildLayout();
Dimension scrDim = Toolkit.getDefaultToolkit().getScreenSize();
setSize(scrDim.width / 2, scrDim.height / 2);
setTitle("Downloader");
setResizable(false);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void buildLayout() {
JLabel label;
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(5, 10, 5, 10);
gbc.gridx = 0;
label = new JLabel("URL:", JLabel.LEFT);
label.setFont(font);
add(label, gbc);
label = new JLabel("Complete:", JLabel.LEFT);
label.setFont(font);
add(label, gbc);
label = new JLabel("Downloaded:", JLabel.LEFT);
label.setFont(font);
add(label, gbc);
gbc.gridx = 1;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
urlTextField = new JTextField(23);
urlTextField.setFont(font);
urlTextField.addActionListener((ActionEvent e) -> {
try {
urlTextField.setEnabled(false);
downloadURL = new URL(urlTextField.getText());
//Start the thread
thread.start();
} catch (MalformedURLException e1) {
JOptionPane.showMessageDialog(null, "Not a valid URL!!", "Error", JOptionPane.ERROR_MESSAGE);
}
});
add(urlTextField, gbc);
progressBar = new JProgressBar(0, 100);
progressBar.setPreferredSize(new Dimension(160, 32));
progressBar.setStringPainted(true);
add(progressBar, gbc);
gbc.gridwidth = 1;
completeLabel = new JLabel(Integer.toString((int)bytesRead));
add(completeLabel, gbc);
gbc.gridx = 2;
gbc.weightx = 0;
gbc.anchor = GridBagConstraints.EAST;
label = new JLabel("Size:", JLabel.LEFT);
add(label, gbc);
gbc.gridx = 3;
gbc.weightx = 1;
sizeLabel = new JLabel(Long.toString(fileSize));
add(sizeLabel, gbc);
}
@Override
public void run() {
try {
performDownload();
} catch (IOException e) {
// Do nothing
}
}
// Get file name portion of URL.
private String getFileName(URL url) {
String fileName = url.getFile();
return fileName.substring(fileName.lastIndexOf('/') + 1);
}
private void performDownload() throws IOException {
// Store (write data) it in the current directory
outputStream = new FileOutputStream(getFileName(downloadURL));
bytesRead = 0;
URLConnection urlConnection = downloadURL.openConnection();
// Get the file size of the url resource
fileSize = urlConnection.getContentLengthLong();
sizeLabel.setText(Long.toString(toMB(fileSize)) + " MB");
// If the file doesn't exists returns -1 !!!
if (fileSize == -1) {
JOptionPane.showMessageDialog(null, "Not a valid URL!!", "Error", JOptionPane.ERROR_MESSAGE);
urlTextField.setEnabled(true);
progressBar.setValue(0);
completeLabel.setText("0");
urlTextField.selectAll();
}
inputStream = new BufferedInputStream(
urlConnection.getInputStream());
buffer = new byte[BUFFER_SIZE];
int byteCount;
while ((bytesRead < fileSize) && (!isStopped)) {
try {
// Read bytes from the InputStream
byteCount = inputStream.read(buffer);
if (byteCount == -1) {
isStopped = true;
break;
} else {
outputStream.write(buffer, 0, byteCount);
bytesRead += byteCount;
progressBar.setValue((int)((bytesRead * 100) / fileSize));
completeLabel.setText(Long.toString(toMB(bytesRead)) + " MB");
}
} catch (IOException ioe) {
isStopped = true;
JOptionPane.showMessageDialog(this,
ioe.getMessage(),
"I/O Error",
JOptionPane.ERROR_MESSAGE);
break;
}
}
try {
// Close the input/output streams
outputStream.close();
inputStream.close();
} catch (IOException ignored) {
}
urlTextField.setEnabled(true);
// In case the user wants to fetch from another URL
thread = null;
thread = new Thread(this);
}
// Converts bytes to MB !!
private long toMB(long bytes){
return bytes/1000000;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(Downloader::new);
}
}
ScreenShot : Imgur
Run the program , enter a url in the textfield , press the Enter key.
The program will fetch the resource from the url and display its progress.
Explanation :
How the program works:
buildLayout() - build the UI of the program
getFileName(Url url) - Gets the filename paortion of the url
performDownload() - downloads the url resource from the Web
toMB(long bytes) - converts the bytes to MB.
We implement the Runnable interface , so that this task can be performed in a separate Thread.
Any long running task must execute in a separate Thread.
we use the OutputStream class to write the data (bytes read) to the disk.
progressbar is used to display the download progress.
we use the URLConnection class to connect to a particular url and fetch it.
getContentLengthLong() returns the file size and is stored in variable fileSize.
we use the InputStream class to read data (bytes) from the url
A while loop is used to loop until bytesRead < fileSize.
byteCount - read bytes from the inputstream
bytesRead = bytesRead + byteCount.
We update the progressbar value in the loop, to show the current progress.
isStopped is a flag variable used to exit the loop under some conditions.
Like for eg ., if the url doesn't exists!!!, then fileSize returns -1.
In that case exit the loop.