Question:
java GUI not Appearing Correctly?
Green
2015-03-25 23:11:23 UTC
I am using jdk8, operating system windows 8.I am learning GUI.
But the problem is that the GUI is not appearing as expected.
Let consider the following code. This program is simple addition
program of two number. When run the program from Eclipse
the output interface is coming like this. photo given.This is
for other Java GUI program I am trying to Build.
What is the cause of it and how can fix it?

import javax.swing.JOptionPane;
public class Addition
{
public static void main( String[] args )
{

String firstNumber =
JOptionPane.showInputDialog( "Enter first integer" );
String secondNumber =
JOptionPane.showInputDialog( "Enter second integer" );


int number1 = Integer.parseInt( firstNumber );
int number2 = Integer.parseInt( secondNumber );

int sum = number1 + number2; // add numbers


JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Sum Integers", JOptionPane.PLAIN_MESSAGE );
}
}
Three answers:
vincentgl
2015-03-26 19:20:57 UTC
You are improperly invoking UI methods that are not thread-safe. You must invoke those methods from code that is being executed by the AWT Event Dispatch thread. Your code is creating and trying to render UI changes from the thread that is executing your main().



Take the body of your main and put it inside "invokeLater" like so:

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

//your code here

}

});



EventQueue.invokeLater takes the Runnable and puts it on the queue for the Event Dispatch thread to execute.
David
2015-03-26 03:27:53 UTC
Your code works perfectly on my system (Win8.1 JDK 8u31)
?
2015-03-26 01:35:35 UTC
have you tried



"The sum is " + String.valueOf(sum)

or

"The sum is " + Integer.toString(sum)


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...