) I have two classes, in the first (WoodyGui) I implemented the GUI, applied an ActionListener to the only JButton and added the TrayIcon to the SystemTray. By responding to the ActionEvent produced by the button I would like all elaboration to be made in the second class (WoodyEng), and once it's done I want it to display a notification on the TrayIcon. But how can I access the trayIcon from the second class? the error message I usually get is:
Exception in thread "Thread-2" java.lang.NullPointerException at WoodyEng.run(WoodyEng.java:27) at java.lang.Thread.run(Unknown Source)
any idea on what I'm missing? why can't I access the TrayIcon reference variabile from the second class like I do (i.e.) with the JButton? Thank you very much for any help...
import java.awt.*;
import java.awt.event.*;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import javax.swing.*;
public class WoodyGui extends JFrame implements ActionListener {
WoodyEng doer = new WoodyEng(this);
JPanel area = new JPanel();
JButton button = new JButton("GO!");
// constructor
public WoodyGui () {
super("woody");
setSize (150,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
button.addActionListener(doer);
area.add(button);
add(area);
setVisible(true);
if (SystemTray.isSupported()) {
final TrayIcon trayIcon = new TrayIcon(new ImageIcon("icon.png", "").getImage(), "tray icon");
final SystemTray tray = SystemTray.getSystemTray();
try {
tray.add(trayIcon);
} catch (AWTException ex) {
System.out.println("TrayIcon could not be added.");
}
}
}
public static void main(String[] arguments) {
WoodyGui pecker = new WoodyGui();
}
}
here there's the second class:
import java.awt.event.*;
import java.awt.SystemTray;
import java.awt.TrayIcon;
WoodyGui gui;
Thread quack;
public WoodyEng (WoodyGui in) {
gui = in;
}
public void actionPerformed(ActionEvent eve) {
Object who = eve.getSource();
if (who == gui.button)
{
if (quack == null) {
quack = new Thread(this);
quack.start();
}
}
}
public void run() {
Thread thisThread = Thread.currentThread();
while (quack == thisThread) {
// all elaboration would occur here
trayIcon.displayMessage("Woody","notification!!",TrayIcon.MessageType.INFO);
if (quack != null) {
quack = null;
}
}
}
}