当我从Eclipse运行但无法从Windows Service(services.msc)运行时,Swing JDialog正常显示 [英] Swing JDialog is showing fine when I run it from eclipse but not working from windows service(services.msc)

查看:68
本文介绍了当我从Eclipse运行但无法从Windows Service(services.msc)运行时,Swing JDialog正常显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在一定时间间隔内运行的Java应用程序,并显示一个弹出窗口(由Java swing制成).当我从eclipse运行应用程序时,它运行良好.在创建一个jar并使用java -jar命令运行它之后,它也可以正常工作.但是当我从Windows service(services.msc)运行jar文件时,没有显示弹出窗口,除了弹出窗口之外,其他所有窗口都正常工作,例如记录数据提取等.我没有找到任何解决方案,因为我已将所有解决方案都应用到了堆栈溢出中,但是问题仍然存在.

I have a java application which runs in a certain interval of time and show a popup(made with java swing). When I run the application from eclipse it works fine. After I created a jar and run it using java -jar command, It is also working fine. But when I run the jar file from windows service(services.msc) Popup window is not appeared, except popup all are working properly such as logging data fetching etc. I did not find any solution for that I have applied all the solution in stack overflow but the problem persist.

我已经粘贴了所有信息.

I have pasted all the information.

预先感谢

Java代码(此方法将在间隔中调用)

Java code (this method will be called in interval)

public static void showUserMsg(final int MsgId, String msgText) {
        logger.info("Entry in showUserMsg to show notification");
        logger.info("Message: " + msgText);

        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        final int screenWidth = (int) dim.getWidth();
        final int screenHeight = (int) dim.getHeight();
        try {
//          JDialog.setDefaultLookAndFeelDecorated(true);
            final JDialog dialog = new JDialog(new JFrame());
            dialog.setTitle("You have message");
            dialog.setAutoRequestFocus(false);
//          dialog.getLayeredPane().getComponent(1).setFont(new Font("Lucida",Font.PLAIN,18)); 
            dialog.setAlwaysOnTop(true);
            dialog.setVisible(true);
            dialog.setSize(600, 450);
            dialog.setLocation(screenWidth / 2 - 250 + 171, screenHeight / 2 - 250);
            dialog.setResizable(true);
            dialog.setModal(false);
            dialog.setModalityType(Dialog.ModalityType.MODELESS);
            dialog.requestFocus();
            final Image img = ImageIO.read(EcsApplication.class.getResource("icons/notify.png"));
            dialog.setIconImage(img);

            logger.info("Dialog location: " + dialog.getLocation());

            Container pane = dialog.getContentPane();
            JTextPane contentLabel = new JTextPane();
            contentLabel.setText("\n\n\n\n\n" + msgText);
            contentLabel.setEditable(false);
            contentLabel.setVisible(true);
            contentLabel.setFont(new Font("Verdana", Font.ROMAN_BASELINE, 18));
            contentLabel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
            contentLabel.setBounds(100, 100, 300, 200);
            JButton okButton = new JButton("Yes, I have read the message");

            okButton.setBounds(120, 330, 400, 50);
            okButton.setFont(new Font("Verdana", Font.ROMAN_BASELINE, 18));
            okButton.setBorder(BorderFactory.createLineBorder(new Color(68, 155, 221), 1));
            okButton.setBackground(new Color(144, 186, 227));
            okButton.setFocusable(true);
            okButton.setVisible(true);

            StyledDocument doc = contentLabel.getStyledDocument();
            SimpleAttributeSet center = new SimpleAttributeSet();
            StyleConstants.setAlignment(center, StyleConstants.ALIGN_CENTER);
            doc.setParagraphAttributes(0, doc.getLength(), center, false);

            pane.add(okButton);
            pane.add(contentLabel);

            dialog.addWindowListener(new WindowListener() {

                @Override
                public void windowOpened(WindowEvent e) {
                }

                @Override
                public void windowClosing(WindowEvent e) {
                    logger.info("windowClosing event");
                    try {
                        statusByMsgId(MsgId);
                        JDialog warning = new JDialog();
                        warning.setTitle("Information");
                        warning.setAlwaysOnTop(true);
                        warning.setVisible(true);
                        warning.setSize(300, 150);
                        warning.setLocation(screenWidth / 2 - 150, screenHeight / 2 - 150);
                        warning.setResizable(false);
                        warning.setModal(true);
                        warning.requestFocus();
                        warning.setIconImage(img);

                        Container pane = warning.getContentPane();
                        pane.setBounds(100, 100, 100, 100);
                        JTextPane warningMsg = new JTextPane();
                        warningMsg.setText("You have read the message");
                        warningMsg.setEditable(false);
                        warningMsg.setVisible(true);
                        warningMsg.setBounds(100, 100, 300, 200);

                        warningMsg.setFont(new Font("Verdana", Font.ROMAN_BASELINE, 14));

                        StyledDocument doc1 = warningMsg.getStyledDocument();
                        SimpleAttributeSet center1 = new SimpleAttributeSet();
                        StyleConstants.setAlignment(center1, StyleConstants.ALIGN_CENTER);
                        doc1.setParagraphAttributes(0, doc1.getLength(), center1, false);

                        pane.add(warningMsg);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        logger.error(ex.getMessage(), ex);
                    }

                }

                @Override
                public void windowClosed(WindowEvent e) {
                }

                @Override
                public void windowIconified(WindowEvent e) {
                }

                @Override
                public void windowDeiconified(WindowEvent e) {
                }

                @Override
                public void windowActivated(WindowEvent e) {
                }

                @Override
                public void windowDeactivated(WindowEvent e) {
                }
            });

            okButton.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    logger.info("OK button clicked.");
                    try {
                        statusByMsgId(MsgId);
                    } catch (Exception ex) {
                        ex.printStackTrace();
//                      InfoLogger.printInfo(EcsService.class, "showUserMsg", "Dialog box not loaded.");
//                      InfoLogger.printExceptionLog("EcsService", "showUserMsg", ex);

                        logger.error(ex.getMessage(), ex);

                    }

                    dialog.setVisible(false);

                }

            });

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        logger.info("Exit in showUserMsg");
    }


创建服务的文件夹结构:

Folder structure to create service:

在classes文件夹中存在java类文件:

Inside the classes folder java class file is present :

public class EcsClientService
{
    Process proc;
    private static EcsClientService serviceInstance;
    private boolean stopped;
    
    public EcsClientService() {
        this.stopped = false;
    }
    
    public static void windowsService(final String[] array) {
        String anObject = "start";
        if (array.length > 0) {
            anObject = array[0];
        }
        if ("start".equals(anObject)) {
            EcsClientService.serviceInstance.start();
        }
        else {
            EcsClientService.serviceInstance.stop();
        }
    }
    
    public void start() {
        this.stopped = false;
        try {
            System.out.println("currentDirectory>>> " + new File(EcsClientService.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParentFile().getAbsolutePath().replace("%20", " "));
            this.proc = Runtime.getRuntime().exec("cmd.exe /c start ECSClientService.bat");
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        while (!this.stopped) {
            synchronized (this) {
                try {
                    this.wait(60000L);
                }
                catch (InterruptedException ex2) {}
            }
        }
    }
    
    public void stop() {
        this.stopped = true;
        synchronized (this) {
            this.notify();
        }
        try {
            Runtime.getRuntime().exec("wmic Path win32_process Where \"CommandLine Like '%ECSClientService.bat%' OR CommandLine Like '%-jar ECSClientService.jar%'\" Call Terminate");
        }
        catch (Exception ex) {}
    }
    
    static {
        EcsClientService.serviceInstance = new EcsClientService();
    }
}

InstallService.bat

InstallService.bat

for /f %%i in ("%20") do set curpath=%%~dpi

common\ecsClient.exe //DS//ECSClientService

common\ecsClient.exe //IS//ECSClientService --Install=%curpath%\common\ecsClient.exe --Description="Employee Communication Service" --Jvm=auto --Classpath=%curpath%\common\classes --StartMode=jvm --StartClass=EcsClientService --StartMethod=windowsService --StartParams=start --StopMode=jvm --StopClass=EcsClientService --StopMethod=windowsService --StopParams=stop --StopMode=jvm --Startup=auto --LogPath=common\logs --StdOutput=auto --StdError=auto


pause


StartService.bat

StartService.bat

common\ecsClient.exe //ES//ECSClientService

StopService.bat

StopService.bat

common\ecsClient.exe //SS//ECSClientService

UninstallService.bat

UninstallService.bat

common\ecsClient.exe //DS//ECSClientService

ECSClientService.bat

ECSClientService.bat

@ECHO OFF
SET CampaignArg=%1
for /f %%i in ("%0") do set curpath=%%~dpi
cd /d %curpath%
java -jar ECSClientService.jar %CampaignArg%
pause

推荐答案

我相信您的问题不在Java中.AFAIK服务在后台运行-无论用户是否登录.因此,他们通常无法访问GUI.

I believe your problem is not in Java. AFAIK services run in the background - regardless whether a user is logged on or not. Thus they usually have no access to the GUI.

如果您的应用程序应在后台运行但在用户上下文中运行,也许您想将应用程序移至自动启动程序文件夹,以便Windows在用户登录时启动它.

If your application shall run in the background but in user context, maybe you want to move your application to the autostart program folder so Windows will start it when a user logs on.

这篇关于当我从Eclipse运行但无法从Windows Service(services.msc)运行时,Swing JDialog正常显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆