Java Reference
In-Depth Information
}
});
pack
();
setLocation
(
500
,
400
);
}
public
public static
static
void
void
main
(
String
[]
args
) {
new
new
JFrameDemo
().
setVisible
(
true
true
);
}
}
This code compiles fine. But when we try to run it, of course, there is no main method. We
need to create one, either inside the
JFrameDemo
class or on its own:
public class JFrameDemoMain {
// We need a main program to instantiate and show.
public static void main(String[] args) {
new JFrameDemo( ).setVisible(true);
}
}
Now we can run it and have it display. But it has two obvious problems: it starts off tiny (on
Windows) or huge (on X Windows). And, when we do resize it, only the buttons show, and it
always takes up the full size of the window. To solve these problems, we need to discuss lay-
out management, to which we will soon turn our attention.
A less obvious problem has to do with thread safety, which we discuss next, in
Run Your
Run Your GUI on the Event Dispatching Thread
Problem
Your application fails to start, with a message like
Running on UI thread when not ex-
pected
. Or, your application crashes very sporadically.
Solution
Run your UI on the UI thread, which Java names the “Event Dispatching Thread” or EDT.