Swing JDialog is showing fine when I run it from eclipse but not working from windows service(services.msc)

huangapple go评论33阅读模式
英文:

Swing JDialog is showing fine when I run it from eclipse but not working from windows service(services.msc)

问题

I have translated the Java code portion of your request. Here it is:

我有一个Java应用程序它在特定的时间间隔内运行并显示一个弹出窗口使用Java Swing制作)。当我从Eclipse运行应用程序时它运行正常但是当我创建一个JAR文件并使用"java -jar"命令运行它时它也正常工作但是当我从Windows服务services.msc运行JAR文件时弹出窗口不会出现除了弹出窗口外所有其他功能都正常工作如日志记录和数据获取等
我没有找到任何解决方案我已经尝试了Stack Overflow上的所有解决方案但问题仍然存在

我已经粘贴了所有信息

提前感谢您

Java代码此方法将在间隔内调用):
以下是您提供的Java代码的翻译

请注意,这只是Java代码的翻译。如果您需要有关其他部分的帮助,请提出具体的问题。

英文:

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.

Thanks In advance

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:

Swing JDialog is showing fine when I run it from eclipse but not working from windows service(services.msc)

Swing JDialog is showing fine when I run it from eclipse but not working from windows service(services.msc)

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

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

common\ecsClient.exe //ES//ECSClientService

StopService.bat

common\ecsClient.exe //SS//ECSClientService

UninstallService.bat

common\ecsClient.exe //DS//ECSClientService

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

答案1

得分: 1

我认为您的问题与Java无关。据我所知,服务在后台运行,无论用户是否登录,因此它们通常无法访问GUI。

如果您的应用程序应该在后台运行但在用户上下文中,也许您想将您的应用程序移动到自动启动程序文件夹,这样Windows会在用户登录时启动它。

英文:

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.

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.

huangapple
  • 本文由 发表于 2020年7月31日 20:36:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63191958.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定