Java programming course: 14.1 JFrame


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:
  • Passes the required title to the superclass constructor
  • Ensures the application is ended when the frame is closed
  • Adds the JPanel object returned from the buildUI() method to the centre of the frame
  • Packs the components and centres the frame on the screen using setLocationRelativeTo(null)

The buildUI() method returns a JPanel which will contain the various UI components shown in this section


Print
×
Stay Informed

When you subscribe, we will send you an e-mail whenever there are new updates on the site.

Related Posts

 

Comments

No comments made yet. Be the first to submit a comment
Saturday, 13 December 2025

Captcha Image