JFrame
In the previous section you saw that the JFrame class can be used to provide a desktop window for your application. For the purposes of this section, you will create a new JFrame that will show various UI components. Define a class called DemoUI in the virtualzoo.ui package:
package virtualzoo.ui;
import java.awt.*;
import javax.swing.*;
public class DemoUI extends JFrame {
public static void main(String[] args) {
new DemoUI().setVisible(true);
}
public DemoUI() {
super("Demonstrate UI Components");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
add(buildUI(), BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
}
private JPanel buildUI() {
JPanel panel = new JPanel(new BorderLayout());
// Components will go here...
// Return the built panel
return panel;
}
}
The class contains its own static
main() method which will allow you to run it independently from the rest of the application. To do this, right-click the DemoUI.java node in the Projects window and select Run;The constructor does the following:
The
- Passes the required title to the superclass constructor
- Ensures the application is ended when the frame is closed
- Adds the
JPanelobject returned from thebuildUI()method to the centre of the frame - Packs the components and centres the frame on the screen using
setLocationRelativeTo(null)
buildUI() method returns a JPanel which will contain the various UI components shown in this section
Comments