Friday, June 05, 2009

A Notification Window in Java

Tray Icon is a nice feature in Java 1.6. Very easy to write an application that sits in the tray and works. The thing that I really needed and didn't find was to show a message from the tray icon in a custom window. Now everywhere I searched I just came across the displayMessage(...) api of the tray icon. This is really useful if you are showing a message like a windows bubble message. Instead if you want to show some custom formatted message in your own window, you are lost, no solution in Tray Icon.

What do we do? Simple write a simple Window in Java Swing that scrolls up from the bottom right corner.

Presented below is a sample program, that shows a scrolling up window. The code is pretty much self explanatory. So without blabbering, here's the code:


public class PopupWindowTest {

private static final long serialVersionUID = 1L;
private static final Integer STARTING_POS_X = 300;
private static final Integer STARTING_POS_Y = 300;

public void showMessage(String text) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Toolkit t = Toolkit.getDefaultToolkit();
JTextArea area = new JTextArea(7, 30);
JPanel panel = new JPanel();
JFrame frame = new JFrame();
final JWindow window = new JWindow();

final JButton ok = new JButton("Click Me");
ok.setSize(40, 20);

final JButton close = new JButton("Close");
ok.setSize(20, 20);

ActionListener listener = new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == ok){
JOptionPane.showMessageDialog(null, "Just a sample message.");
} else if (e.getSource() == close){
window.dispose();
}
}};

ok.addActionListener(listener);
close.addActionListener(listener);

area.setEditable(false);
area.setOpaque(true);
area.setAutoscrolls(true);
area.setText(text);
area.setBackground(new Color(202,219,243));

JScrollPane spane = new JScrollPane(area,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
spane.setBorder(BorderFactory.createEtchedBorder());

panel.setBackground(new Color(203,222,148));
panel.add(spane);
panel.add(ok);
panel.add(close);

frame.getContentPane().add(panel);
frame.pack();

window.setLocation((int) (t.getScreenSize().getWidth() - STARTING_POS_X),
(int) (t.getScreenSize().getWidth() - STARTING_POS_Y));
window.setContentPane(frame.getContentPane());
window.setBounds(0, 0, 265, 168);
window.setAlwaysOnTop(true);

for (int i = 300; i < 450; i = i + 1) {
window.setLocation(
(int) (t.getScreenSize().getWidth() - STARTING_POS_X),
(int) (t.getScreenSize().getWidth() - i));
window.setVisible(true);
}
}


public static void main(String[] args) throws Exception {
new PopupWindowTest().showMessage("The message goes here");
}
}

No comments:

Post a Comment