Swing Application Window not responding on Mac - java

I'm trying to get a basic Swing Application to run on my Mac OS X 10.8.2 (Java version 1.6.0_37) machine, and every time I try to run it from Eclipse, the frame appears, but I can't interact with it.
I've tried to start from a basic, clean slate where I create a new Swing Application Window project in Eclipse (WindowBuilder->Swing Designer->Application Window). This generates the following skeleton code:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.BorderLayout;
public class Test {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
window.frame.pack();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton btnPress = new JButton("Press");
frame.getContentPane().add(btnPress, BorderLayout.CENTER);
}
}
Everything seems to be fine, but when I run this from Eclipse, the frame doesn't let me interact with any components (in my non-example code, there are buttons and tabs).
Also, in the console, I see things like:
2012-11-09 14:30:27.624 java[8107:707] [Java CocoaComponent compatibility mode]: Enabled
2012-11-09 14:30:27.626 java[8107:707] [Java CocoaComponent compatibility mode]: Setting timeout for SWT to 0.100000
Is there some Mac-specific setting that I have to change? (I'm using the latest default Mac JRE)

The program runs fine on my machine under OSX, but it could be the missing
window.frame.pack();
Have you tried this?
Test window = new Test();
window.frame.pack();
window.frame.setVisible(true);

I had the same problem when using the DJ Swing library in my application (it uses SWT). Interestingly, the problem occurred even though I didn't initialise DJ Swing explicitly. It now works because I have added DJ Swing initialisation:
public class SwingAppTest {
public static void main(String[] args) {
NativeInterface.open();
UIUtils.setPreferredLookAndFeel();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame("Example");
frame.getContentPane().setLayout(new BorderLayout());
frame.setPreferredSize(new Dimension(400, 200));
frame.setBounds(0,0,200,200);
frame.setTitle("blah");
JButton blah = new JButton("blah");
blah.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("button clicked");
}
});
frame.getContentPane().add(blah, BorderLayout.CENTER);
frame.setVisible(true);
}
});
NativeInterface.runEventPump();
}
}

Apple is no longer supporting Java in is operating systems after 10.6:
Apple not committing to Java support in Mac OS X 10.7
seems like missing or incompatible library files in the JRE.

that is weird. I tried your sample (no linux) and don't see any problem there.
So as Wayne mentioned, might be macos issue.
Btw, what is your java version you're using?
On the other hand problem might be in the code you didn't share with us => hard to guess :)
EDIT: OK, so it seems you're playing "guess what I have in my code" game with us :) As my assumption is that code not shown causes problem.
It reminds me of some of these Poiroit/Agatha Christie detective stories, where just a little detail might have significant impact on the reality.
This is the reason for my theory:
code shown uses Java swing library (import javax.swing. ...) + Awt (import java.awt. ...) - this combonation is a common use case, however
the error message you shared shows SWT library error (Setting timeout for SWT to 0.100000)
So to me it seems like you're mixing things that should never be mixed.
As Swing is java UI library that is completely OS independent (originally Sun made) that is built on top of Awt. However SWT is completely different java UI library which is kind of mix of native calls with java on it (originally IBM made).
Therefor I'd suggest to double check your code and make sure that if you use JFrame, the only library components you have there are from Swing (javax.swing....) / Awt (java.awt. ...).

I've been knocking my head against a wall for days trying to get this working and finally found the answer:
'It's solved now - it was just a case of removing swt.jar from the project dependencies.'
Hey presto!!!!

In my case, I was trying to code a game where I used jPanel. I needed to override the paint method and added pack(); to the main and it finally showed me what I was trying to draw.

Related

Java with GUIs won't run

Hi I need help with Java on my mac. I've cleanly uninstalled all versions of Java and installed the Oracle JDK 1.8.0_202. I can do javac and java - and compile and run simple programs running in the console. However - when I try anything with a window - it hangs.
This includes all gui applications, java web starts and even the Java control panel won't launch - it simply stops responding and does not show anything.
This simply application also behaves the same:
import javax.swing.*;
public class HelloWorldSwing {
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Add the ubiquitous "Hello World" label.
JLabel label = new JLabel("Hello World");
frame.getContentPane().add(label);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I've tried reinstalling, rebooting, anything, and I still cannot get this simple program to run. I get no error messages in the terminal from where I run this - it just freezes.
Please help me troubleshoot this and get a working java setup.
I'm using a Macbook pro with Mojave 10.14.3
EDIT
Actually the real culprit is Display Link. If you ever have issues with Java and GUIs - it might be because you are using Display Link and the drivers are conflicting with Java. Only if your laptop screen is closed though.
See this for more information
https://displaylink.org/forum/showthread.php?t=66556
I hope this can help

How to force ImageJ to close all its windows without close event error?

I am writing a Java application for image analysis which at one point opens ImageJ with
ImageJ ij = new ImageJ();
and also opens a Windows containing an ImagePlus.
Now, whenever one closes ImageJ first, the ImagePlus will not close when pushing the close button. The other way around works, however in both cases an exception is thrown after closing ImageJ:
java.lang.reflect.InvocationTargetException
at java.awt.EventQueue.invokeAndWait(EventQueue.java:1288)
at java.awt.Window.doDispose(Window.java:1209)
at java.awt.Window.dispose(Window.java:1147)
at ij.ImageJ.run(ImageJ.java:784)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: null source
at java.util.EventObject.<init>(EventObject.java:56)
at java.awt.AWTEvent.<init>(AWTEvent.java:337)
at java.awt.event.InvocationEvent.<init>(InvocationEvent.java:285)
at java.awt.event.InvocationEvent.<init>(InvocationEvent.java:174)
at sun.awt.X11.XBaseMenuWindow.dispose(XBaseMenuWindow.java:907)
...
I don't know whether it is related as it happens in both cases.
Any suggestions on how to force ImageJ to close all its windows?
The exception
This happens when using OpenJDK 7 on Linux. The exception is fixed in Java 8.
Also: note that that exception is not the actual cause of the quitting issue you are seeing.
The disposal problem
ImageJ 1.x's application disposal is a convoluted mess. (See this news post for some technical discussion.) It was really intended primarily to run as a standalone application, and is mostly tested with the exitWhenQuitting flag set to true such that the JVM shuts down upon closure of the main window. So it is not surprising that using ImageJ in a different fashion results in hanging image windows.
I have tested various workarounds—e.g.:
ij.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(final WindowEvent e) {
// dispose all image windows
for (final int id : WindowManager.getIDList()) {
final ImagePlus imp = WindowManager.getImage(id);
if (imp == null) continue;
final ImageWindow win = imp.getWindow();
if (win != null) win.dispose();
}
// dispose all other ImageJ windows
for (final Window w : WindowManager.getAllNonImageWindows()) {
w.dispose();
}
}
});
But none of them work as one might hope. It cost me weeks of development and experimentation to make quitting work as we wanted in ImageJ2, according to the news posted linked above.
Here is some code using ImageJ2 that almost behaves the way you want:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import net.imagej.ImageJ;
public class IJDispose {
public static void main(final String... args) {
final ImageJ ij = new ImageJ();
ij.ui().showUI();
final JFrame frame = new JFrame("Hello");
final JButton b = new JButton("Close ImageJ");
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
ij.getContext().dispose();
}
});
frame.getContentPane().add(b);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
After launching it, press Shift+B to open the Blobs sample image. Then click the "Close ImageJ" button from the non-ImageJ frame. You'll see that the ImageJ main window and the image window dispose as desired (using this code from ImageJ Legacy).
However, there are (at least) three problems:
This example does not hook up the ij.getContext().dispose() call to the actual ImageJ1 UI window closing event. And doing that would not be trivial (I say without having dug deeply in this code recently).
After disposing ImageJ, as well as the extra JFrame, the JVM is supposed to shut down. We put a lot of effort into making it do so, actually. But it actually doesn't with the current version of ImageJ, presumably due to some undisposed resource(s) somewhere. This is a bug.
Clicking the X on the main ImageJ window shuts down the entire JVM, because ImageJ1's exitWhenQuitting flag gets set to true. You could toggle it back to false yourself, but this is actually tricky due to class loading issues relating to the fact that ImageJ2 patches ImageJ1 at runtime using Javassist.
The next question is: How badly do you really need this to work?

Why is Java crashing on even the simplest Swing program?

For seemingly no reason, Java has started crashing whenever I try to run anything with Swing. If I run the HelloWorld program, for example, just to test things, it'll run perfectly fine. But if I try to run a program with a JFrame, no matter how simple (I even tried the JFrame demo example on Java's website just so I could get a bare-bones JFrame program), I always get the "Java SE Platform Binary has stopped working" error.
Could this be related to a graphics driver update? I'd think not but you never know.
This is the demo I tried:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FrameTest {
public static void main(String[] args) {
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(175, 100));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
You should always use SwingUtilities.invokeLater() when dealing with Swing from main() or from any thread that isn't EDT.
https://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
Still I am not allowed to post a comment. That is why I answer even for simple things.
Go to Environment variables.
Under the System Variables, click on new.
In the variable name, enter _JAVA_OPTIONS
In the Variable Value, enter -Xmx256M
Press OK and Check if it works now.

JFrame gets decorated with Windows borders, even the Look&Feel is set otherwise

Good day everyone.
First of all: check this image.
Please note that in the first of the 3 frames, the button is styled with Metal Look and Feel, but the frame is Windows styled. The other 2 frames are "OK" in the sence that the button LAF matches the frame LAF.
The code for all of these (same order as the images):
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.getContentPane().add(new JButton("button"));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
frame.setSize(100, 100);
frame.getContentPane().add(new JButton("button"));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
// 0 => "javax.swing.plaf.metal.MetalLookAndFeel"
// 3 => the Windows Look and Feel
String name = UIManager.getInstalledLookAndFeels()[3].getClassName();
UIManager.setLookAndFeel(name);
} catch (Exception ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame();
frame.getContentPane().add(new JButton("button"));
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
Now what bothers me is that I have never been forced to use the lines frame.setUndecorated(true); frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);, as setting the Look and Feel just worked with the UIManager.setLookAndFeel() method. Normally, the JFrame itself would get styled too, but this seems not longer the case as I get a Windows styled frame (1st image, 1 code snippet).
Why is this? Is this new in Java 7? This seems really weird.
Normally, without touching code that involves Look and Feel, the program should start with the Metal Look and Feel, as this is the standard Java Look and Feel. So why does the first program start with a Windows frame?
Add this line in your main method before you init the JFrame
JFrame.setDefaultLookAndFeelDecorated(true);
I noticed the same thing a while ago when I started using substance but that line is all it took to fix it.
As the preceding code snippet implies, you must invoke the setDefaultLookAndFeelDecorated method before creating the frame whose decorations you wish to affect. The value you set with setDefaultLookAndFeelDecorated is used for all subsequently created JFrames. You can switch back to using window system decorations by invoking JFrame.setDefaultLookAndFeelDecorated(false). Some look and feels might not support window decorations; in this case, the window system decorations are used.
That's from Oracle in reference to that line of code.
This is a feature of Java, by default JFrame Window borders will not be decorated, but using the mentioned function allows the set look and feel to decorate the Window. This feature was implemented in 1.4 from what I can tell.
Edit:
Also, if you want to apply your custom look and feel to JDialog window borders, you can use the same static method on the JDialog class in the same place you called it on JFrame:
JDialog.setDefaultLookAndFeelDecorated(true);
I'm guessing that you hane not set the swing.defaultlaf system environment variable, but maybe you could check if your swing.properties is present and if it contains an entry swing.defaultlaf. This could be the reason, see below for how the UIManager chooses L&F.
I have the file present on my MacBook, obviously, as Apple wants the Apple L&F to be the default. But I have not checked a Windows machine yet..
Here's an excerpt from the Java 7 documentation which has been pretty much unchanged since Java 1.4. Java 1.4.2, Java 1.5, Java 6, Java 7:
Default look and feel
The class used for the default look and feel is chosen in the following
manner:
If the system property swing.defaultlaf is
non-null, use its value as the default look and feel class
name.
If the Properties file swing.properties
exists and contains the key swing.defaultlaf,
use its value as the default look and feel class name. The location
that is checked for swing.properties may vary depending
upon the implementation of the Java platform. In Sun's implementation
the location is ${java.home}/lib/swing.properties.
Refer to the release notes of the implementation being used for
further details.
Otherwise use the cross platform look and feel.

Why my Swing based GUI application is not responding?

I am trying to create my first GUI application using (Java + Eclipse + Swing). This is my code:
import java.awt.*;
import javax.swing.*;
public class HelloWorldSwing extends JFrame {
JTextArea m_resultArea = new JTextArea(6, 30);
//====================================================== constructor
public HelloWorldSwing() {
//... Set initial text, scrolling, and border.
m_resultArea.setText("Enter more text to see scrollbars");
JScrollPane scrollingArea = new JScrollPane(m_resultArea);
scrollingArea.setBorder(BorderFactory.createEmptyBorder(10,5,10,5));
// Get the content pane, set layout, add to center
Container content = this.getContentPane();
content.setLayout(new BorderLayout());
content.add(scrollingArea, BorderLayout.CENTER);
this.pack();
}
//============================================================= main
public static void main(String[] args) {
JFrame win = new HelloWorldSwing();
win.setTitle("TextAreaDemo");
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setVisible(true);
}
}
The code was taken from here.
When I run the application from Eclipse the expected window appears (So, it's good. I see what I want to see). However, when I try to close the window or try to write something in the text area the program freezes. The OS writes me that program is not responding (I try it on Ubuntu).
Can anybody help me to find the reason of the problem?
Thank you in advance for any help.
I'm sure this doesn't have to do with the code, as others have found the code runs just fine on their machines - which points to a machine specific issue. From within Eclipse, make sure it is setup to use the expected JDK/JRE. However, before worrying about how Eclipse is handling your situation, I'd run things by hand first - especially since you've got a very simple class.
I would check to ensure that you're using the expected compiler and runtime. On Linux:
which javac
which java
If they're both what you expect, do the following:
javac HelloWorldSwing.java
java HelloWorldSwing
If you get a similar problem, then you know it's not the Eclipse configuration and it's something else. If you're not using the latest JDK, upgrade to the latest. If you're already at the latest, it could be a display driver. Do other JAVA swing programs work on this computer? I'm sure you could find some on the net, download an app already packaged as a jar and try running it.
did you try using the eventdispatcherthread to view the JFrame?
something like:
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
createAndViewJFrame();
}
});
}
public void createAndViewJFrame(){
JFrame win = new HelloWorldSwing();
win.setTitle("TextAreaDemo");
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setVisible(true);
}
then your frame would be shown by the swing dispatcher thread.
hope it helped, although im just guessing...
Update: as commenters pointed you i f**ed up the invokeLater() call. I just edited this post to correct that. Thanx go to yishai & willcodejavaforfood for pointing it out!
frank
You need to catch the exit event and
respond with a System.exit( 0 );
You should be able to find that in
most swing examples online.
wrong stuff... sorry... coffee... argh....

Categories