- HeadlessException on Windows 10 machine
- HeadlessException при попытке запуска оконного приложения
- Java Tools /
- Инструменты
- Exception in thread “AWT-EventQueue-0” java.awt.HeadlessException
- 1 Answer 1
- Not the answer you’re looking for? Browse other questions tagged java liferay awt or ask your own question.
- Related
- Hot Network Questions
- Subscribe to RSS
- How to avoid HeadlessException in thread?
- 2 Answers 2
- LWJGL java.awt.HeadlessException thrown when making a JFrame
- Trying to achieve
- The problem
- What I tried
- 1 Answer 1
- Solution to the problem:
- I recommend:
HeadlessException on Windows 10 machine
I’m trying to show a message using Swing but when I create it I receive this error message:
Exception in thread «AWT-EventQueue-0» java.awt.HeadlessException at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:204) at java.awt.Window.(Window.java:536) at java.awt.Frame.(Frame.java:420) at java.awt.Frame.(Frame.java:385) at javax.swing.SwingUtilities$SharedOwnerFrame.(SwingUtilities.java:1758) at javax.swing.SwingUtilities.getSharedOwnerFrame(SwingUtilities.java:1833) at javax.swing.JOptionPane.getRootFrame(JOptionPane.java:1696) at javax.swing.JOptionPane.showOptionDialog(JOptionPane.java:863) at javax.swing.JOptionPane.showMessageDialog(JOptionPane.java:666) at javax.swing.JOptionPane.showMessageDialog(JOptionPane.java:637) at javax.swing.JOptionPane.showMessageDialog(JOptionPane.java:608) at sintel.onetouch.online.controle.ControlePrincipal$1.run(ControlePrincipal.java:272) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756) at java.awt.EventQueue.access$500(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.awt.EventQueue$3.run(EventQueue.java:703) at java.security.AccessController.doPrivileged(Native Method)
This is a chunk of the code:
I’m running it on a Windows 10 machine, on netbeans IDE.
I already tried to use JavaFX instead Swing but it gives me other problems. I tried to execute on a new thread, using swing worker like the code above.
HeadlessException при попытке запуска оконного приложения
Java Tools /
Инструменты
Всем привет! Недавно перешёл к Linux (Fedora 21). И вот столкнулся с первой проблемой. Написал простую оконную программку.
Компиляция прошла успешно, но при попытке запустить приложение выводится следующее:
Exception in thread «main» java.awt.HeadlessException
at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:207)
at java.awt.Window. (Window.java:536)
at java.awt.Frame. (Frame.java:420)
at javax.swing.JFrame. (JFrame.java:225)
at my_programs.xo.TicTacToeGUI.startGame(TicTacToeGUI.java:287)
at my_programs.xo.TicTacToeGUI.main(TicTacToeGUI.java:33)
Подскажите, пожалуйста, в чём дело? Может быть какие-нибудь компоненты нужно установить для работы с графическими приложениями на Федора.
Заранее спасибо.
А вы покайтесь, откуда джаву установили?
У вас она стартует в режиме без загрузки графических ништяков (это актуально для сервера например). Такое может быть ещё если у вас какие-то переменные среды для дисплея в линуксе не видны. Но это имхо редкость.
при вводе команды java -version выводится:
openjdk version «1.8.0_25»
OpenJDK Runtime Environment (build 1.8.0_25-b18)
OpenJDK 64-Bit Server VM (build 25.25-b02, mixed mode)
Что? Не тот JDK скачал?
А «which java» вам показывает откуда java запускается? И куда вы ставили скачанный JDK?
Я подозреваю что скачали вы тот, но запускаете не тот. OpenJDK вместо HotSpot например.
А куда вы установили тот JDK который скачали? Перейдите в него, в папку bin и попробуйте оттуда java запустить (в частности для своей программы).
Вот и узнаем, что там насчёт разницы 😉
Не так много у вас наверное обнаружится файлов и папок с названиями вроде java или jdk*
И как именно вы устанавливали с помощью yum с сайта?
ну можете просто полный путь указать:
или в этом духе.
Если это окажется то что надо, то просто в /usr/bin замените java на символическую ссылку в нужный каталог.
Exception in thread “AWT-EventQueue-0” java.awt.HeadlessException
so i want to integrate this in liferay. i trying to get this application when i click on submit button. previously i done it in java web application now i just deployed in portlet but its running in java not in liferay i am getting this exception i am using java version7 somehow everything works fine except this error it been stuck for a long while.
1 Answer 1
Whatever aadhar application you have, it seems to be a java desktop application, which you can’t run on the web. It obviously tries to start up a dialog (JFrame) in that stacktrace: You’ll have to write some kind of web application for it. If you have the UI components already fully written in Java, the closest that comes to this programming style is probably vaadin, which is integrated in Liferay, but can also be updated to a newer version.
However, any AWT application just will not work.
Not the answer you’re looking for? Browse other questions tagged java liferay awt or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
How to avoid HeadlessException in thread?
I have tried to open a dialog box in Servlet & it opens fine. But then I tried to achieve same thing in my thread’s run method. It gaved me following error:
Below is my code :
I also tried below code, but failed
Exception is described as : Thrown when code that is dependent on a keyboard, display, or mouse is called in an environment that does not support a keyboard, display, or mouse.
2 Answers 2
Java servlet code runs at webserver, not at webclient (webbrowser). All the webserver does is listening on HTTP requests, producing HTML/CSS/JS responses and sending it to the webclient. All the webclient does is sending HTTP requests and processing the retrieved HTML/CSS/JS responses.
If you execute Swing GUI in the servlet, it will be displayed in the webserver, not in the webclient.
There are basically 3 solutions for this particular problem:
Run Swing GUI code at webclient instead. You can do that in flavor of an Applet or Web Start which get served by a JSP/HTML page.
Use a client side programming/scripting language instead, e.g. JavaScript or ActionScript (Flash). In JavaScript there’s an alert() function which displays a dialog.
Use taglibs like JSTL and/or EL in JSP to render HTML/CSS/JS content conditionally. Can eventually be combinied with solution #2.
There is code which eventually needs to touch a graphics card, or at least a working graphics subsystem in Java. If you run this code on a system which doesn’t have graphics enabled, then you will throw a HeadlessException.
You are running your code in a Servlet, which is a chunk of code that typically returns a web page. Since the web page is one big string containing all of the proper tags, the web page doesn’t need a graphical environment. That string is received by a web browser, and the web browser generally has a graphical environment to display the results.
On your web server, you are asking the web page generator (the servlet) to open up a dialog box. This creates problems for a number of reasons:
- The dialog box would show up on the web server, not on the web client.
- The web server has only one screen, and the dialog boxes will pop up according to the people browsing the web page.
- Since the server potentially might handle many clients simultaneously, the server is tuned to use a minimum amount of resources for each client.
- Since the server only returns items to web browsers, the server doesn’t need a graphical environment.
All of these points combined means that the servlet won’t be configured to have access to a graphics environment, and there will be no opportunity to display a pop-up dialog; because, there is no graphical environment available to display a dialog.
In general, you can’t mix swing / awt code with servlets; however, there is a subset of Graphics operations available in both swing and awt which allow image manipulation without needing a graphical environment. This is to ease the development of transforming and building images in a file processing environment, where the images will never be displayed by the program. Think of a .png to .jpg converter as an example, provided it never shows the image, the program could open Image(s) do its work, and close the images without needing a graphics card.
LWJGL java.awt.HeadlessException thrown when making a JFrame
Hi I’m working on a group project and the code works on my teammate’s PCs but I keep hitting MacOS specific errors. And this time I seem to be stuck (no easily Googleable answer).
In a previous post I discovered I need » -Djava.awt.headless=true » as VM setting to properly run my simulation. Now when I try to spawn in some JFrame they are all met with a lovely » java.awt.HeadlessException » Exception because of that VM flag.
Trying to achieve
I want to be able to spawn those JFrames on my MacBook also.
The problem
I need -Djava.awt.headless to be both true and false at the same time for my program to run properly on Mac. Which if I understand my problem correcly, means I have a big problem on my hands.
EDIT: running it in a VM on my Macbook allowed me to run the project properly. This is far from an ideal fix. I’m still searching for a solution to this obscure problem.
What I tried
- not running with the VM option: the problem described in previous post occurs. Thus this is not a viable option
- running with the VM option: this throws a -Djava.awt.headless when creating a JFrame.
1 Answer 1
The best way to fix this may be by going back and solving your original problem a different way.
You must make sure that you are not initializing your BufferedImage in the main thread (GLFW thread), it MUST be done separately. It is hard to tell from your original question, but that looks like part of the cause there. Start a new thread to do the image processing instead.
See my solution and recommendation at the bottom of this answer for a quick summary, and also see here for someone else that had the same issue: Java Creating Instance of BufferedImage Freezes Program
A quick note on why your code works on Windows and not Mac: that is because both OS often run different implementations of openGL, and typically Mac can lag behind and miss out on a bunch of updates/changes that may solve problems like this one so that it doesn’t freeze when initializing a BufferedImage on the openGL thread.
If the above didn’t work then lets first look at what headless mode is. (Emphasis mine):
See link at bottom for full article and more info.
Headless mode is a system configuration in which the display device, keyboard, or mouse is lacking. Sounds unexpected, but actually you can perform different operations in this mode, even with graphic data.
Where it is applicable? Let’s say that your application repeatedly generates a certain image, for example, a graphical authorization code that must be changed every time a user logs in to the system. When creating an image, your application needs neither the display nor the keyboard. Let’s assume now that you have a mainframe or dedicated server on your project that has no display device, keyboard, or mouse. The ideal decision is to use this environment’s substantial computing power for the visual as well as the nonvisual features. An image that was generated in the headless mode system then can be passed to the headful system for further rendering.
So when should headless mode be used:
On a machine that has no display device, keyboard, or mouse.
That is not you is it? However if that is you (LWJGL?), then lets look at how you can work with headless mode:
An image that was generated in the headless mode system then can be passed to the headful system for further rendering.
This means that you should have a special piece of headless code that does your headless image stuff, but then passes the image back to a normal JFrame with a head.
So why does it fail for you:
Many components are affected if a display device, keyboard, or mouse is not supported. An appropriate class constructor throws a HeadlessException
- Button
- Checkbox
- Choice
- Dialog
- FileDialog
- Frame
- Label
- List
- Menu
- MenuBar
- MenuItem
- PopupMenu
- Scrollbar
- ScrollPane
- TextArea
- TextField
- Window
Solution to the problem:
some classes, such as Canvas or Panel, can be executed in headless mode.
Perfect, so we just need to be careful what is used in headless mode. You asked how you can both use and not use headless mode, well rather than globally setting headless mode with VM option -Djava.awt.headless you can do it programmatically within your code using System.setProperty(«java.awt.headless», «true»); where needed. A JFrame should be normal (not Headless), but you can spawn a JPanel as headless without issue.
I recommend:
You create a normal headed main thread with no VM option that spawns JFrames, and then use that main thread to spawn a new child thread and set your LWJGL bits in that thread to be headless, and that way you can run your LWJGL code without issue, and at the same time you can still have JFrames from your main thread. Remember to make sure that the Buffered image is not done in the main LWJGL/OpenGL thread.