Swing: User Interfaces in Java
Java has a fairly rich framework for creating user interfaces "out of the box". That framework is called Swing. Before learning Swing, it's worth making sure that you really understand the following:- the basic concepts of object-oriented programming (e.g. the notion of classes, object creation, inheritance);
- basic Java syntax: how to call methods, how to create loops etc;
- interfaces, in the programming sense.
Introduction to the Swing and user interface packages
Many of the Swing classes representing windows, lists, buttons etc live in the javax.swing package and subpackages. The names of most Swing classes start with the letter J: JFrame, JPanel, JButton, JList etc. In general, if you're looking for the class that represents some visual component in Swing, its name will start with J.A few classes also live in the java.awt package and subpackages. AWT stands for Abstract Window Toolkit and was in some sense the precursor to Swing. AWT provides a bare-bones way of creating a user interface, based directly on "native" user interface components of the operating system. Swing actually builds on AWT, and some AWT classes are still used directly in Swing programming. For example, many of the classes responsible for laying out user interface components lie inside the java.awt package, and many classes to do with handling events live in java.awt.event; the Graphics interface, which represents a graphics context and is key to rendering graphics inside a window or component, is also originally part of the AWT package.
Example: a first Swing application
By way of a vary basic example which we will extent on the next page, the following application displays a window:import javax.swing.JFrame; public class MyApp { public static void main(String[] args) { // Actually slightly incorrect from a threading point of view JFrame frame = new JFrame("My Swing app"); frame.setSize(500, 500); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
The call to set the size of the window is hopefully self-explanatory once you see it; let us just comment for now that in general, you need to think about the size (and potentially layout) of all windows/components when you're programming with Swing. The call to setDefaultCloseOperation() is a shortcut we can use in the very simple case where we want our application to exit when the window is closed: Swing will dutifully call System.exit() for us. We'll see later that we can customise what happens when a window is closed.
0 comments:
Post a Comment