Runtime problems with HelloWorldSWT eclipse - java

I just downloaded Eclipse and was doing the HelloWorldSWT tutorial to familiarize myself with the IDE.
The program runs, but contrary to having display.sleep() in the main loop, the program continues to eat up CPU cycles. Is this normal for this tutorial? and how can I prevent this?
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
public class HelloWorldSWT {
/**
* #param args
*/
public static void main(String[] args) {
Display display = new Display();
Shell shell = new Shell(display);
shell.setText("Hello world!");
shell.open();
while(!shell.isDisposed()){
display.sleep();
}
display.dispose();
shell.close();
}
}
Edit: I've found that
if (!display.readAndDispatch()) {display.sleep();}
resolves the issue. However, I still do not understand the difference between checking for nonexistant events and then telling the display to sleep and just telling the display to sleep that would cause this issue.

You need to call display.readAndDispatch() to read the events from the event queue and act on them (dispatch).
Even the the deactivate event from the Shell must be dispatched!
All SWT based application have an event loop as the one you have added to your post. Have a look at the SWT Snippets for more examples.

It is how you create the project that is causing this. The correct relationships need to be applied at the start with dependencies set and libraries set.
I got it working then played around with it to see what was underlying cause as there are a lot of blogs with various tips that worked with some people and not with others.
Main point is this is necessary
import org.eclips.swt.widget.Display
import org.eclips.swt.widget.Screen

Related

Linux Mint Cinnamon Lock-Up Debugging w/Eclipse

I have a reproducible problem with the Mint Cinnamon desktop locking up when hitting a breakpoint debugging with Eclipse. When I say it's locking up, I mean mouse clicks are completely inoperable (even on the Mint panel), but the mouse cursor still moves. Keyboard is unresponsive, except for some OS-level shortcuts like Alt-Tab. Alt-Tab looks like it's working, but selecting another window doesn't actually focus or activate the window (only the Alt-Tab selector popup works). I can only recover using Ctrl-Alt-ESC to restart Cinnamon. Everything proceeds fine after that.
Debugging and breakpoints work fine everywhere else as far as I can tell except when the breakpoint is inside an anon inner class or lambda.
Public git repo with a fairly simple example project causing this:
https://bitbucket.org/jfxexamples/eclipseminttest
Linux Mint 17.3 AND a totally new install of Mint 18 on a different PC - both behave the same
Eclipse Neon 4.6.0
Java 8 (1.8.0_92) - Oracle JDK (Using JavaFX)
Code below (you'll have to grab the project files to run it though):
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
BorderPane root = (BorderPane)FXMLLoader.load(getClass().getResource("Sample.fxml"));
Scene scene = new Scene(root,400,400);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
package application;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
public class SampleController {
#FXML
private TabPane tabPane;
public void createTab() {
Tab tab = new Tab("New tab");//Breakpoint here does NOT freeze desktop
// tab.setOnCloseRequest(e -> {
// System.out.println("bleh");//Breakpoint here, freezes desktop
// });
tab.setOnCloseRequest(new EventHandler<Event>(){
#Override public void handle(Event e){
System.out.println("bleh");//Breakpoint here, also freezes desktop
}
});
tabPane.getTabs().add(tab);//Breakpoint here does NOT freeze desktop
int index = tabPane.getTabs().size() - 1;
tabPane.getSelectionModel().select(index);
}
}
Using Win10/IntellijCE/JDK1.8.0_92 there is no problem. Try using IntellijCE on Mint. If it works the problem is most likely with Cinnamon.
Cinnamon is on Github, so use their Issue Tracker there to report the bug.
Browsing the issues, there is even something maybe related to your issue: Check out https://github.com/linuxmint/Cinnamon/issues/1084.
I have had exactly the same problem in Linux Mint 17.3 Mate, with JDK 1.8.0_101, Eclipse Neon and a JavaFX application.
When debugging the application, the system freezes completely and I have to kill the process manually.
It seems a problem related with the X display. It should work if you set, in the VM arguments of your application, the flag:
-Dsun.awt.disablegrab=true
At least that worked for me...
This is a known problem on Linux. It is related to the XGrabPointer and XGrabKeyboard API calls (see X Pointer Grabbing). This API can be used by screensavers, so it is intended to make the keyboard and mouse unusable (apart from moving the mouse cursor).
During debugging, it is a problem. In the past, a workaround was to configure AllowDeactivateGrabsin xorg. That allowed to break the "grap" by a keyboard shortcut, by default CTRL+ALT+/. Since it was possible to bypass screensavers, it was disabled around 2012 because of its security implications.
On a modern Linux system, you can enable enable grab break actions:
setxkbmap -option grab:break_actions
Now, you can trigger a grab break by executing:
xdotool key XF86Ungrab
Once your keyboard is frozen, you might be not able to run it, so during debugging, I am calling it every two seconds:
while :; do sleep 2 ; xdotool key XF86Ungrab ; done
Notes:
setxkbmap is part of xorg-setxkbmap
xdotool is part of xdotool
While testing the setup, it is useful to have a ssh connection from another machine. Thus, if mouse and keyboard freeze up, you can always kill the process that grabbed the mouse and keyboard.

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?

I can't run a JFrame due to compiler errors & warnings

*I'm sorry for all of the trouble I may have caused you guys.
So, I am extremely new to programming with just a little experience in Java and Python. I was trying to make a program that would open a frame. In this frame there would be a button. When clicked, this button would play a song. I used a "recommended" code from YouTube. The code would begin to run, and then just stop. No frame would ever even appear. I showed it to a more experienced friend of mine. He said that the exact code ran just fine on his computer. I then sent him a screenshot of my project displayed on eclipse. He said that my JRE seemed to be missing some files. I tried a code that would just create a window, but it had the same problem. I am not sure what the JRE is, but I currently have JRE7. I don't know what I should do to fix this. Please help.
Error List
Severity and Description Path Resource Location Creation Time Id
The public type TopLevelWindow must be defined in its own file TGProject/src Frame.java line 4 1390698271752 73
The type TopLevelWindow is already defined TGProject/src TopLevelWindow.java Unknown 1390699351785 77
The method show(boolean) from the type Component is deprecated TGProject/src sound.java line 16 1390702839525 78
A link to the what my eclipse shows.
http://gyazo.com/3afdfa4f6750420f4e46deec40389340
A link to my Java file.
http://gyazo.com/257481d4ae9e2bb1d0ca93415a6c547e
Code for music
import java.awt.event.*;
import javax.swing.*;
import sun.audio.*;
import java.io.*;
public class sound {
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(200,200);
JButton button = new JButton("Click me");
frame.add(button);
button.addActionListener(new AL());
//this is outdated, but should still work
frame.show(true);
}
public static class AL implements ActionListener{
public final void actionPerformed(ActionEvent e) {
music();
}}
public static void music()
{
AudioPlayer MGP = AudioPlayer.player;
AudioStream BGM;
AudioData MD;
ContinuousAudioDataStream loop = null;
try{
BGM = new AudioStream(new FileInputStream("Jambi.mp3"));
MD = BGM.getData();
loop = new ContinuousAudioDataStream(MD);
}catch(IOException error) {}
MGP.start(loop);
}
}
Code for Frame
import java.awt.*;
import javax.swing.*;
// Create a simple GUI window
public class TopLevelWindow {
private static void createWindow() {
//Create and set up the window.
JFrame frame = new JFrame("Simple GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel textLabel = new JLabel("I'm a label in the window",SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
frame.getContentPane().add(textLabel, BorderLayout.CENTER);
//Display the window.
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
createWindow();
}
}
Error 1
The public type TopLevelWindow must be defined in its own file
You either need to change.
public class TopLevelWindow {
To:
class TopLevelWindow {
Or do as reported and declare a new class for TopLevelWindow
Error 2
The type TopLevelWindow is already defined
I'm not sure what that means, but it might be solved by fixing the first problem.
Warning 3
The method show(boolean) from the type Component is deprecated
For any deprecation warning, go to the relevant method in the Java Docs. They should give details about what to use instead.
Tips
Compile often and ask as soon as you have a single error you do not understand.
Don't try to run code that shows problems in that window. Only experts should even try that.
You catch more flies with honey than with vinegar. Don't take the tone you did with Jayan, even if you think they are being harsh. People help for free, so have little time for questions that do not come up to standard. It might have been better to explain to the person that the question had now changed. Perhaps that would have made no difference to them, but either way, adding that kind of reply discourages everyone from helping.
"I used a "recommended" code from YouTube." Don't use YouTube videos to learn programming. They are often old, and in this case, they are using classes in the sun package for which there were better replacements since Java 1.3.
If you're really that new to programming, I would suggest to use an IDE (development environment) like for instance Netbeans or Eclipse and create a new JFrame form. You can then use the design view to graphically design your interface, IE drag your button on the screen. No need to go around programming frames. All you need to code is the implementation; what happens after you click the button.
After you posted the code, I had another look and this is what I've found:
Both classes have main methods. I ran both and each opened up a different window for me. Typically, you'll only want one main method. It's the main method! It's the starting point of your program and you can of course only have one starting point. At this time, your program is going to do two different things depending on what main method you run.
Still, this isn't your issue, because both mains are running for me. I think you must have the wrong version of java or something?
What I think you did is you pasted all that code into a file that wasn't called exacly "TopLevelWindow". If so, do that. I think your problem will go away.
Remember to only have one class per file, (barring inner classes; not something to concern yourself with as a beginner).

Java gui colors dont load

I've made a gui for my program and used
UIManager.put("Button.background", new Color(0,0,0));
UIManager.put("JButton.background", new Color(0,0,0));
to make the buttons appear black. Unfortunately, this doesn't work sometimes. Without modifying the code, it will work when I run it one time and wont work another time.
The following image is the same button in the same program after several times I ran it. This happens about 1 in 4 times I run the program.
(left button is correct and the right one is what sometimes happens while running)
Also, other things like
UIManager.put("control", new Color(15,0,0));
are loading properly. Never had a problem with it and it's loaded at the same time and same format.
EDIT: Here's a sample code where the button colors aren't loading at all while the background and other things are. They are loaded the same exact way and there are no compilation or run errors.
import java.awt.*;
import javax.swing.*;
import javax.swing.UIManager.*;
public class gtst
{
public static void main(String[] args) throws Exception
{
UIManager.put("Button.background", new Color(1,1,1));
UIManager.put("JButton.background", new Color(1,1,1));
UIManager.put("control", new Color(0,0,0));
UIManager.put("text", new Color(255,220,0));
Frame batFrame = new JFrame("nananananna Batman!");
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
{
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
String username = JOptionPane.showInputDialog(batFrame, "Enter something...:");
}
}
How I usually do this is I make a button as a seperate JButton variable and then add that to my panel. Then to set the color of the button I use the code:
myButton.setBackground(Color.BLACK);
and that usually does the trick.
Try using the following code after you have made the changes in the UIManager:
SwingUtilities.updateComponentTreeUI(<your_root_ui_componenet>);
After days of non stop trial and error, I figured out that apparently in my program the MySQL connection was causing the problem. If the MySQL connection was initiated at the start of the program and the color changes were too this cause some sort of a problem (maybe lag?) and the colors wouldn't always load. Maybe it's a problem with the MySQL driver or something else, not sure, but to fix it I just made it connect to MySQL when it needed the connection rather than at the program start.
I'm not sure why the colors didn't load at all in the example I provided.

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