Thursday 11 October 2012

Upload and Save Image in Swings

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;

public class ImageCopy extends JFrame implements ActionListener {
    JMenuItem fMenuOpen = null;
    JMenuItem fMenuSave = null;
    JMenuItem fMenuClose = null;
    JTextArea fTextArea;
    static JLabel label;
    static BufferedImage icon;
    static File oldfile;
    JFileChooser fc;
    ImageFilter1 fJavaFilter = new ImageFilter1();
    static File fFile;

    public ImageCopy(String title) {
        // TODO Auto-generated constructor stub

        super(title);
        Container content_pane = getContentPane();
        content_pane.setLayout(new BorderLayout());

        JMenu m = new JMenu("File");
        m.add(fMenuOpen = makeMenuItem("Open"));
        m.add(fMenuOpen = makeMenuItem("Save"));
        m.add(fMenuClose = makeMenuItem("Quit"));
        JMenuBar mb = new JMenuBar();
        mb.add(m);
        setJMenuBar(mb);
        setSize(400, 400);
    }

    public void actionPerformed(ActionEvent e) {
        boolean status = false;
        String command = e.getActionCommand();
        if (command.equals("Open")) {
            try {
                status = openFile();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            if (!status)
                JOptionPane.showMessageDialog(null, "Error opening file!",
                        "File Open Error", JOptionPane.ERROR_MESSAGE);
        } else if (command.equals("Save")) {
            status = saveFile();
            if (!status)
                JOptionPane.showMessageDialog(null,
                        "IO error in saving file!!", "File Save Error",
                        JOptionPane.ERROR_MESSAGE);
        } else if (command.equals("Quit")) {
            dispose();
        }
    }

    private JMenuItem makeMenuItem(String name) {
        JMenuItem m = new JMenuItem(name);
        m.addActionListener(this);
        return m;
    }

    boolean openFile() throws IOException {
        JFileChooser fc = new JFileChooser();
        fc.setDialogTitle("Open File");
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        fc.setCurrentDirectory(new File("."));
        fc.setFileFilter(fJavaFilter);
        int result = fc.showOpenDialog(this);
        if (result == JFileChooser.CANCEL_OPTION) {
            return true;
        } else if (result == JFileChooser.APPROVE_OPTION) {

            fFile = fc.getSelectedFile();
            oldfile = fFile;
            System.out.println(fFile);
            FileInputStream fileInputStream = new FileInputStream(fFile);
            System.out.println(fileInputStream);
            System.out.println(fFile.getAbsolutePath());
            icon = ImageIO.read(fileInputStream);
            label = new JLabel(new ImageIcon(icon));
            label.setBounds(0, 0, 500, 500);
            label.setVisible(true);
            getContentPane().add(label);
            // Set the position of its text, relative to its icon:
            label.setVerticalTextPosition(JLabel.BOTTOM);
            label.setHorizontalTextPosition(JLabel.CENTER);
        } else {
            return false;
        }
        return true;
    }

    boolean saveFile() {
        File file = null;
        fc = new JFileChooser();
        javax.swing.filechooser.FileFilter filter = null;
        fc.setCurrentDirectory(new File("."));
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        fc.addChoosableFileFilter(filter);
        filter = fc.getFileFilter();
        fc.setFileFilter(fJavaFilter);
        fc.setSelectedFile(fFile);
        int result = fc.showSaveDialog(this);
        if (result == JFileChooser.CANCEL_OPTION) {
            return true;
        } else if (result == JFileChooser.APPROVE_OPTION) {
            fFile = fc.getSelectedFile();
            if (fFile.exists()) {
                int response = JOptionPane.showConfirmDialog(null,
                        "Overwrite existing file?", "Confirm Overwrite",
                        JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE);
                if (response == JOptionPane.CANCEL_OPTION)
                    return false;
            }
            return writeFile(fFile, label);
        } else {
            return false;
        }
    }

    public static boolean writeFile(File file, Object component) {
        try {

            BufferedImage i1 = ImageIO.read(oldfile);
            BufferedImage bi = new BufferedImage(i1.getWidth(), i1.getHeight(),
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = bi.createGraphics();
            ImageIO.write(i1, "png", fFile);
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
        String title = "Frame Test";
        if (args.length != 0)
            title = args[0];
        ImageCopy f = new ImageCopy(title);
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.setVisible(true);
    }

}

class ImageFilter1 extends javax.swing.filechooser.FileFilter {
    public boolean accept(File f) {
        return f.getName().toLowerCase().endsWith(".png")
                || f.getName().toLowerCase().endsWith(".jpg")
                || f.getName().toLowerCase().endsWith(".jif")
                || f.isDirectory();
    }

    public String getDescription() {
        return "Image files (*.png)";
    }

}

Tuesday 11 September 2012

Checking for Null or Empty or White Space Only String in Java

/**
 * Demonstrate checking for String that is not null, not empty, and not white
 * space only using standard Java classes.
 *
 * @param string String to be checked for not null, not empty, and not white
 *    space only.
 * @return {@code true} if provided String is not null, is not empty, and
 *    has at least one character that is not considered white space.
 */
public static boolean isNotNullNotEmptyNotWhiteSpaceOnlyByJava(
   final String string)
{
   return string != null && !string.isEmpty() && !string.trim().isEmpty();
}


Refer:
http://marxsoftware.blogspot.in/2011/09/checking-for-null-or-empty-or-white.html

Struts2 Date Format

<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Struts 2 Format Date Example!</title>

<link href="<s:url value="/css/main.css"/>" rel="stylesheet"
type="text/css"/>

</head>
<body>


<s:form action="FormatDate" method="POST">


<tr>
<td>Date in (yyyy-MM-dd) Format:</td>
<td>
<b><s:date name="todayDate" format="yyyy-MM-dd" /></b>
</td>
</tr>

<tr>
<td>Date in (MM/dd/yyyy hh:mm AM/PM) Format:</td>
<td>
<b><s:date name="todayDate" format="MM/dd/yyyy 'at' hh:mm a" /></b>
</td>
</tr>

<tr>
<td>Date in (dd-MMM-yyyy hh:mm AM/PM) Format:</td>
<td>
<b><s:date name="todayDate" format="dd-MMM-yyyy 'at' hh:mm a" /></b>
</td>
</tr>

<tr>
<td>Date in (dd/MM/yyyy hh:mm) Format:</td>
<td>
<b><s:date name="todayDate" format="dd/MM/yyyy hh:mm" /></b>
</td>
</tr>

<tr>
<td>Nice Format:</td>
<td>
<b><s:date name="todayDate" format="yyyy-MM-dd" nice="true"/></b>
</td>
</tr>

</s:form>

</body>

</html>



Monday 28 May 2012

Upload an image in swings


package basic;

import java.io.*;

import javax.swing.*;

import java.awt.Button;
import java.awt.Label;
import java.awt.event.*;

public class JLabelUploadImage {
static File file;
static JFrame frame;
private static JLabel label1;
static ImageIcon icon;


public static void main(String[] args) {
// final JPanel panel = new JPanel();
frame = new JFrame("Upload Image");
frame.setLayout(null);
label1 = new JLabel();

label1.setBounds(300, 300, 300, 100);
frame.add(label1);

final JFileChooser fc = new JFileChooser();
Button browse = new Button("Browse File");
browse.setBounds(200, 300, 40, 30);
frame.add(browse);
browse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int returnval = fc.showOpenDialog(null);
if (returnval == JFileChooser.APPROVE_OPTION) {
file = fc.getSelectedFile();
System.out.println(file.getName());
}
}
});
Button button = new Button("Upload Image");
button.setBounds(100, 300, 40, 30);
frame.add(button);

button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent ae) {
System.out.println("upload");
String path = file.getAbsolutePath();
System.out.println(path);
icon = new ImageIcon(path);
label1.setIcon(icon);
frame.add(label1);

System.out.println(icon.getIconHeight());

}

});
frame.add(browse);
frame.add(button);
frame.setSize(700, 700);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Saturday 12 May 2012

Overriding


Q>What is the Output of this code?

class Parent {
    Number get() {
        return 1;
    }
}

class Child extends Parent {
    Integer get() {
        return 2;
    }
}

public class Test {
    public static void main(String[] args) {
        Parent yo = new Child();
        System.out.println(yo.get());
    }
}

***Output is in comment.

SCJP questions on Exception Handling


Q>What is the Output of this code?

public class Test {
public static void main(String[] args) {
for (int a = 0; a < 10; ++a) {
try {
if (a % 3 == 0)
throw new Exception("Except1");
try {
if (a % 3 == 1)
throw new Exception("Except2");
System.out.println(a);
} catch (Exception inside) {
a *= 2;
} finally {
++a;
}
} catch (Exception outside) {
a += 3;
} finally {
++a;
}
}
}
}


***Answer is in Comment