Java JFrame freezing - java

I have this simple java application using swing. However the moment I execute the program the frame will appear but I won't be able to click anywhere and the button only appears after a few seconds. I am very new to javas Swing library so I could be missing something, however from what I've read this code shouldn't be causing any issues.
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
import java.awt.FlowLayout;
import javax.swing.*;
public class Game {
public static void main(String[] args) {
JFrame frame = new JFrame("JFrame Example");
JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel label = new JLabel("This is a label!");
JButton button = new JButton();
button.setText("Press me");
panel.add(label);
panel.add(button);
frame.add(panel);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
EDIT
So I reinstalled my jdk but discovered this: if my browser is running when I execute the above code it will hang and freeze, however if I close my browser it runs as expected. But I can't start my browser until I kill my application so it seems something is wrong with my install as these shouldn't be using the same resources?
EDIT
Solved my problem: had multiple versions of jdk and jre install so unstalled both and then installed latest versions and everything seems to be working!

You need to create UI under UI dispatching thread:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// code to create UI or call to function that creates the UI
}
});
Java 8 style:
SwingUtilities.invokeLater(()->{
// Your UI code
});
If you don't use that idiom then the UI can't be partially created in inconsistent state, see Creating UI in swing:
almost all code that creates or interacts with Swing components must
run on the event dispatch thread
You can also use invokeAndWait is you need to block until the UI is created.

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

Indeterminate JProgressBar animation lag

Using the following code
package scrollbartest;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
public class ScrollBarTest {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JProgressBar b = new JProgressBar();
b.setIndeterminate(true);
b.setPreferredSize(new Dimension(400, 20));
f.add(b);
f.pack();
f.setVisible(true);
});
}
}
the progressbar "indefinite" animation is very laggish. What am I doing wrong?
Some more information:
OS: debian 9.8
The code seems to work smoothly on other OS (tried on Windows)
Happens both with oracle JDK 1.8.0_201 and OpenJDK 1.8.0_181
Continuously moving the mouse cursor over the main JFrame lets the
animation run smoothly
The effect changes with selected look and feel: GTK+ is better than
system default, but the effect is still there
Because of the fourth point, I think it is a sort of slow "refresh time"... can this be possible?
Thanks for any help!
UPDATE:
Doing some research, I found out that the indeterminate progress bar animation can be controlled setting some parameters in the current look and feel:
ProgressBar.repaintInterval
ProgressBar.cycleTime
Unfortunately, some look and feels seems to ignore the first parameter, while some other seems not. For instance, MetalLookAndFeel seems to ignore it, resulting in laggish animation, with a repaint time of around 0.5 seconds, while NimbusLookAndFeel seems to use it.
Try adding the below line to enable video acceleration, if not enabled in your OS:
System.setProperty("sun.java2d.opengl", "true");

Intellij, "contentPane cannot be set to null" using swing designer

I'm trying out intellij, and am trying to do some swing development. I am running into an issue I have never experienced on eclipse, and I am wondering if I have something set up wrong.
Here is my GUI class that is run by my driver:
package view;
import javax.swing.*;
import java.awt.*;
public class View {
private JPanel panel;
public void run() {
JFrame frame = new JFrame("Vending Machine");
frame.setContentPane(new View().panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer
* >>> IMPORTANT!! <<<
* DO NOT edit this method OR call it in your code!
*
* #noinspection ALL
*/
private void $$$setupUI$$$() {
final JPanel panel1 = new JPanel();
panel1.setLayout(new GridBagLayout());
}
}
as far as I can tell, my run() method is as straightforward as it gets. However, upon compiling, this is the error I receive:
Exception in thread "main" java.awt.IllegalComponentStateException: contentPane cannot be set to null.
at javax.swing.JRootPane.setContentPane(JRootPane.java:621)
at javax.swing.JFrame.setContentPane(JFrame.java:698)
at view.View.run(View.java:13)
at model.VendingMachine.<init>(VendingMachine.java:14)
at controller.Driver.main(Driver.java:14)
For whatever reason, the intellij autocreated code that does not properly initialize the JPanel, which is why it's null.
I've tried instantiating it myself inside run (panel = new JPanel();) but that has not helped.
Is this something obvious? I've never run into this issue when getting started with swing in eclipse.
You are setting as JFrame' s content pane the panel 'panel' but the JPanel you are creating is called 'panel1'. To fix this problem change JPanel' s name to 'panel' instead of 'panel1'.
Try enabling "UI Designer" plugin in Intellij IDEA, it helped in my case.
File -> Settings -> Plugins -> UI Designer -> Restart IDE
You need to make sure to to set the field name of the panel. You are possibly misunderstanding the following line:
frame.setContentPane(new View().panel);
In this code, new View().panel is really trying to initialize the object with the field name. So if the panel doesn't have that name...obviously you are trying to instantiate something that doesn't exist.
I named my JPanel MainPanel under the field name property in the jform editor and wrote:
frame.setContentPane(new View().MainPanel);

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.

Swing Application Window not responding on Mac

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.

Categories