我为我的应用程序构建了一个非常简单的通知系统,这是完整的类:
public class Notification extends JFrame {
Timer timer;
private static int count = 0;
private String from;
private String msg;
private String time;
private final JLabel jLabel1;
private final JLabel jLabel2;
private final JLabel jLabel3;
private final JLabel jLabel4;
public void NotificationStart(int seconds) {
timer = new Timer();
timer.schedule(new RemindTask(), seconds*1000);
}
class RemindTask extends TimerTask {
public void run() {
System.out.format("Remove notification");
timer.cancel(); //Terminate the timer thread
dispose(); // Remove the window
count--;
}
}
public Notification(String from, String msg, String time) {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
getContentPane().setLayout(null);
setSize(308,77);
setBackground(new Color(0, 255, 0, 0));
setLocationRelativeTo(null);
setUndecorated(true);
setAlwaysOnTop(true);
jLabel2.setFont(new java.awt.Font("Lucida Grande", 1, 12));
jLabel2.setText(from + ":");
jLabel2.setBounds(38, 11, 240, 15);
jLabel1.add(jLabel2);
jLabel3.setFont(new java.awt.Font("Lucida Grande", 0, 12));
jLabel3.setText(msg);
jLabel3.setBounds(38, 25, 240, 50);
jLabel1.add(jLabel3);
jLabel4.setBounds(280, 6, 16, 16);
jLabel1.add(jLabel4);
// Start timer
NotificationStart(8);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/notification.png")));
getContentPane().add(jLabel1);
jLabel1.setBounds(0, 0, 308, 77);
// Position it
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice defaultScreen = ge.getDefaultScreenDevice();
Rectangle rect = defaultScreen.getDefaultConfiguration().getBounds();
int x = (int) rect.getMaxX() - (this.getWidth() + 10);
int y;
if(this.count == 0) {
y = (int) rect.getMinY() - 46 + this.getHeight();
} else {
y = (int) rect.getMinY() + 30 + (this.getHeight() * this.count);
}
this.setLocation(x, y);
this.setVisible(true);
this.count = count + 1;
jLabel1.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
// Remove notification if user clicks it
dispose();
}
public void mouseEntered(MouseEvent e) {
// Show the close icon
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/icnClose.png")));
}
public void mouseExited(MouseEvent e) {
// Hide the close icon
jLabel4.setIcon(null);
}
});
}
要生成通知,我在主 JFrame 中使用以下代码:
new Notification("Thomas", "New notification!", "13.25");
只要我在 NetBeans 中运行代码,一切都完全按照我想要的方式工作。如果我从 NetBeans 执行清理和构建并尝试运行可执行 jar,则应用程序将停止。
我知道错误在这个类中,因为如果我没有从我的主 JFrame 的任何地方调用 Notification 类,jar 执行得很好。
有任何想法吗?