Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

Java 7 new feature : Determining the file content type

Program to demonstrate Java 7 new feature : Determining the file content type.

package com.hubberspot.nio;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileContentType {

    public static void main(String[] args) {
        
        printContentType("D:/Downloads/java.txt");
        printContentType("D:/Downloads/java.ppt");
        printContentType("D:/Downloads/java.doc");
        printContentType("D:/Downloads/java.jar");

    }

    private static void printContentType(String pathToFile) {
        
        Path path = Paths.get(pathToFile);
        String contentType = null;
        try {
            contentType = Files.probeContentType(path);
        } catch (IOException e) {
     
            e.printStackTrace();
        }
        System.out.println("File content type is : " + contentType);
        
    }

}



Output of the program : 

 

How to set different Look and Feel in Java Swing ?.

A simple Java program to set different installed look and feel in Java Swing

package com.hubberspot.swing;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;

class LookAndFeel extends JFrame {

    private JPanel panel;
    private JTextField textField;
    
    public LookAndFeel() {
     
        setTitle("Look And Feel Demo");
        setSize(300, 200);
        
        panel = new JPanel();
        
        textField = new JTextField("Metal look and feel");
        textField.setBackground(Color.cyan);
        
        LookAndFeelInfo[] installedLookAndFeels = UIManager.getInstalledLookAndFeels();
        
        for(LookAndFeelInfo lookAndFeel : installedLookAndFeels) {
            
            final String name = lookAndFeel.getName();
            final String className = lookAndFeel.getClassName();
            
            JButton button = new JButton(name);
            panel.add(button);
            
            button.addActionListener(new ActionListener()
            {
               public void actionPerformed(ActionEvent event)
               {
                  try
                  {
                     UIManager.setLookAndFeel(className);
                     SwingUtilities.updateComponentTreeUI(LookAndFeel.this);
                     textField.setText(name + " look and feel");
                  }
                  catch (Exception e)
                  {
                     e.printStackTrace();
                  }
               }
            });
        }
        
        panel.add(textField);
        add(panel);
         
    }
}


public class LookAndFeelTest {

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                LookAndFeel frame = new LookAndFeel();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }

}   



Output of the program : 




 

Observer Design Pattern in Java

What is Observer Design Pattern in Java ?.

The Gang of Four book (Design Patterns: Elements of Reusable Object-Oriented Software, 1995, Pearson Education, Inc. Publishing as Pearson Addison Wesley) says that the Observer design pattern should

"Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically."

Example : Let's say there is Weather Broadcasting company which broadcast weather changes to its subscribers. The subscribers or observers such as News Channels , News Paper Agencies and Weather Information Provider websites etc ... gets updated as soon as weather changes by the Weather Broadcasting company. Let's see how we can implement this Subject - Observer model in Java.

Program to demonstrate how to implement Observer Design Pattern in Java.

1. Subject.java
package com.hubberspot.designpattern.behavioral.observer;

public interface Subject {
    
    public void addObserver(Observer observer);
    
    public void removeObserver(Observer observer);
    
    public void notifyObservers();

}


2. Observer.java
package com.hubberspot.designpattern.behavioral.observer;

public interface Observer {
    
    public void update(int temperature);

}


3. WeatherBroadcast.java
package com.hubberspot.designpattern.behavioral.observer;

import java.util.ArrayList;
import java.util.List;

public class WeatherBroadcast implements Subject {

    private List< Observer > listOfObservers;
    private int temperature;    
    
    public WeatherBroadcast() {
        listOfObservers = new ArrayList< Observer >();
    }
    
    @Override
    public void addObserver(Observer observer) {
        
        listOfObservers.add(observer);
        
    }

    @Override
    public void removeObserver(Observer observer) {
        
        listOfObservers.remove(observer);        
        
    }

    @Override
    public void notifyObservers() {
        
        for(Observer observer : listOfObservers) {
            observer.update(temperature);
        }
        
    }
    
    public void temperatureChanged(int newTemperature) { 
        temperature = newTemperature;
        notifyObservers();
    }

}


4. NewsPaperAgency.java
package com.hubberspot.designpattern.behavioral.observer;

public class NewsPaperAgency implements Observer {

    @Override
    public void update(int temperature) {

        System.out.println("News Paper Agencies gets current temperature as: "
                + temperature + " degrees");

    }

}


5. NewsChannel.java
package com.hubberspot.designpattern.behavioral.observer;

public class NewsChannel implements Observer {

    @Override
    public void update(int temperature) {

        System.out.println("News Channel gets current temperature as: "
                + temperature + " degrees");

    }

}


6. WeatherInfoWebsite.java
package com.hubberspot.designpattern.behavioral.observer;

public class WeatherInfoWebsite implements Observer {

    @Override
    public void update(int temperature) {

        System.out.println("Weather Info Websites gets current temperature as: "
                + temperature + " degrees");

    }

}


7. ObserverDesignPatternTest.java
package com.hubberspot.designpattern.behavioral.observer;

public class ObserverDesignPatternTest {

    public static void main(String[] args) throws InterruptedException {

        WeatherBroadcast weatherBroadcast = new WeatherBroadcast();

        Observer newsPaperAgency = new NewsPaperAgency();
        Observer newsChannel = new NewsChannel();
        Observer weatherInfoWebsite = new WeatherInfoWebsite();

        weatherBroadcast.addObserver(newsPaperAgency);
        weatherBroadcast.addObserver(newsChannel);
        weatherBroadcast.addObserver(weatherInfoWebsite);
        
        weatherBroadcast.temperatureChanged(30);
        
        System.out.println("\nAfter 2 minutes temperature changes to 33 degrees...\n");
        
        Thread.sleep(120000);
        
        weatherBroadcast.temperatureChanged(33);

    }

}


Output of the program : 

 



Video tutorial to demonstrate how to implement Observer Design Pattern in Java.







 
© 2021 Learn Java by Examples Template by Hubberspot