Tag Archives: java swing

Windows GUI File Parser using Groovy

I find myself doing a lot of file parsing on my Windows XP machine lately. I decide to write a quick utility that would allow me to drag and drop files and search for the key words that I have identified. The utility doesn’t have the logic for searching using regex’s yet, but it should be really easy to add this functionality.

I hacked some Groovy Code with some Java Code and came up with the following script. Hope it is useful.

DISCLAIMER:

As the title suggests, I have only been able to get this to work on my Windows XP machine, OS X didn’t like the javax.swing.TransferHandler and it appears some other operating systems have a hard time with this also.


import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.awt.BorderLayout;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.TransferHandler.*;

class FileDropHandler extends TransferHandler {

private static final long serialVersionUID = 1L;

def wordsToFind =[]
JTextArea output
private JLabel errorMsg;
private String fileText = "";
private boolean test = false;
private boolean same = true;

public boolean canImport(TransferSupport supp) {
/* for the demo, we'll only support drops (not clipboard paste) */
if (!supp.isDrop()) {
return false;
}

/* return false if the drop doesn't contain a list of files */
if (!supp.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
}

boolean copySupported = (COPY & supp.getSourceDropActions()) == COPY;

if (copySupported) {
supp.setDropAction(COPY);
return true;
}

return false;
}

public boolean importData(TransferSupport supp) {
if (!canImport(supp)) {
return false;
}

/* get the Transferable */
Transferable t = supp.getTransferable();

try {

Object data = t.getTransferData(DataFlavor.javaFileListFlavor);

List fileList = (List) data;

for (int j = 0; j < fileList.size(); j++) { File file = (File) fileList.get(j); //file.getAbsolutePath() def tmpfh = new File("FileParser.txt") println wordsToFind.inspect() new File(file.getAbsolutePath()).eachLine{line->
wordsToFind.each{ if(line =~ "${it}" ){
println "${line}"
tmpfh.append(line)
tmpfh.append("\n\n")
this.output.setText(this.output.getText()+line+"\n")
}
}
}//end for

tmpfh.close()

}
} catch (UnsupportedFlavorException e) {
return false;
} catch (IOException e) {
return false;
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

return true;
}

public void setOutput(JTextArea jta) {
this.output = jta;
}

public void setOutput(JLabel jta) {
errorMsg = jta;
}

public String getText() {
return fileText;
}

public void clearAll() {
fileText = "";
test = false;
same = true;

}
}

class AL implements ActionListener{
public JTextField jtf
public FileDropHandler dh
public AL(JTextField jtf,FileDropHandler dh){
this.jtf = jtf
this.dh =dh
}
public void actionPerformed(ActionEvent actionEvent){
println "${this.jtf.getText()}"
dh.wordsToFind= this.jtf.getText().split(' ')
}
}

JTextArea dTextArea = new JTextArea("Drop on me");
FileDropHandler dh = new FileDropHandler()
dh.setOutput(dTextArea)
JTextField jta = new JTextField("Enter words seperated by spaces")
dh.wordsToFind= jta.getText().split(' ')
JButton jb =new JButton("Update Word List")
jb.addActionListener( new AL(jta ,dh ))

dh.setOutput(dTextArea);
dTextArea.setDragEnabled(true);
dTextArea.setTransferHandler(dh);

JPanel p =new JPanel(new BorderLayout());
JFrame f = new JFrame()
p.add(jta, BorderLayout.NORTH)
p.add(dTextArea, BorderLayout.CENTER)
p.add(jb, BorderLayout.SOUTH)

f.getContentPane().add(p)
f.setSize(400,400)
f.setVisible(true)

A Groovy Flickr API

A long time ago I wanted to write a desktop GUI interface for Flickr. At the time I had just learned Java and thought it would be really cool to write it using swing. Little did I know how not cool working with swing would be 🙁

About halfway through the project I heard about a cool new dynamic way to write Java code called Groovy. From that day on Groovy has been making my life a whole lot easier. I didn’t need all the functionality in the flickrj library, so I decide to write a few methods for my app using Groovy. The hardest part of the whole thing was figuring out how to post images to Flickr, for that, I used the flickrj code as a reference. If that source code was not available, I don’t think I would have ever figured it out. So a big thanks to all the folks working on that project!

This is not a complete API for Flickr, but should provide enough to get started.
Link to my GitHub Repo

Rotating Java Images

I am working on a swing flickr app and thought I would share some code to help those that are new to java gui programming( like me) and get them on their way to making their killer application.

I’ll start off with my first problem,  “How do I show an Image?” After looking through Java forums and going through my Java books, I settled on using Image Icons in JLabels. The next thing I wanted to do was rotate the image 90 degrees. I used Java’s Graphics class to accomplish this. The following groovy code loads 100 JLabels containing a JPEG of Pixar’s Wall-e that I had in the same directory rotated 90 degrees.

import java.awt.image.BufferedImage
import javax.swing.*
import java.awt.*;
import java.util.*;
import java.awt.image.AffineTransformOp
import java.awt.geom.AffineTransform

class ImageButton extends JLabel{
	ImageIcon picture

public ImageButton(ImageIcon icon){
	super(icon)
	this.setBackground(Color.BLACK)
	this.setForeground(Color.BLACK)
	this.picture=icon
	this.setPreferredSize(new Dimension(120,100))
}

public void rotateImage( int angle) {
	int w = this.picture.getImage().getWidth()
	int h = this.picture.getImage().getHeight()
	BufferedImage bi = new BufferedImage(w,h,
                      BufferedImage.TYPE_INT_RGB)
	Graphics bg = bi.createGraphics();
	bg.rotate(Math.toRadians(angle), w/2, h/2);
	bg.drawImage(this.picture.getImage(),0,0,w, h,
			0,0,w, h, null);

	bg.dispose()//cleans up resources
	this.setIcon(new ImageIcon(bi))
	this.setPreferredSize(new Dimension(this.picture.getIconHeight(),
                       this.picture.getIconWidth()))
	}
}

JFrame f= new JFrame()
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
JPanel panel=new JPanel();
def img= new ImageIcon("walle.jpg")
(1..100).each{i->
	def btn=new ImageButton(new ImageIcon(img.getImage()
                        .getScaledInstance(120,100,4)))
	panel.add(btn)
	btn.rotateImage(90)//rotate the image now
	println i
}

panel.setBackground(Color.BLACK)

f.setSize(300,400)
f.getContentPane().add(panel)
f.setVisible(true)

 

My first few attempts at the code gave me out of memory Heap errors. I unknowingly had BufferedImage references hanging around.  Once I realized this, I cleaned up my code and remembered to call dispose() on the graphics bg object and everything came together quite nicely.