Reminder Copy-on-Focus

| No Comments

Another Reminder update. I realised that, if I send several messages over the wire, only the last one gets copied to the clipboard. Well, no more, now if you have multiple message windows open and you click on one, it's text is copied to the clipboard. If you want to change what's on the clipboard, you just click another one. The source file to do this is available after the flip. Props to Freenode's ##java for helping me figure out WindowAdapter.

Reblog this post [with Zemanta]
package Reminder;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.logging.Handler;
import java.util.logging.Logger;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JWindow;

public class DistributedReminderGUI
    extends WindowAdapter
    implements Runnable, ClipboardOwner {

    private static Logger logger = Logger.getLogger("Reminder");
    private DistributedReminderGUIHistory historyView;

    public DistributedReminderGUI() {
	Handler messageLog = null;
	messageLog = (Handler)new DistributedReminderHandler();
	messageLog.setFormatter(new DistributedReminderXMLFormatter());

	logger.addHandler(messageLog);
    }

    public void copyToClipboard(String content) {
	Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
	StringSelection selection = new StringSelection(content);
	cb.setContents((Transferable)selection, this);
    }

    // ClipboardOwner
    public void lostOwnership(Clipboard clipboard, Transferable contents) { 
	return;
    }

    JTextField field = new JTextField();
    // Runnable
    public void run() {
	DateFormat now = DateFormat.getDateTimeInstance();
	try {
	    Toolkit.getDefaultToolkit().beep();
	    JFrame frame = new JFrame(now.format(new Date()));
	    frame.addWindowFocusListener(this);
	    field.setText(System.getProperty("reminder.notificationMessage"));
	    field.setEditable(false);
	    frame.add(field);
	    frame.pack();
	    frame.setVisible(true);
	    this.copyToClipboard(field.getText());
	} catch (java.awt.HeadlessException e) {
	}
	logger.info(System.getProperty("reminder.notificationMessage"));
    }

    // WindowAdapter
    public void windowGainedFocus (WindowEvent e) {
	String contents = field.getText();
	this.copyToClipboard(contents);
	logger.info("Clipboard contents: "+contents);
    }
}

Leave a comment

Bookmark and Share

Connect with me


qrcode
Add me on AOL
Hasan Diwan

Follow me on Twitter
Ring me at +1 6502844111
See my photos
How about some analytics?

Twitter

Archives

Creative Commons License
This blog is licensed under a Creative Commons License.