Get up to 80 % extra points for free! More info:

Lesson 2 - Java Swing under the hood

In the previous lesson, Introduction to form applications in Java Swing, we programmed our first form application in Java. Or rather, we used the designer to create it. In today's lesson, we'll explain how it works inside.

Under the hood

The form itself is, of course, an object (obviously :) ). It's defined by the MainJFrame class, which we can find in the file.

Let's switch to the class code using the "Source" button. Some parts of the code are greyed out and collapsed. When we expand the whole code and remove comments, it looks like this (don't get scared :) ):

public class MainJFrame extends javax.swing.JFrame {

    public MainJFrame() {

    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();


        jLabel1.setText("Greetings from the form");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
                .addGap(41, 41, 41)
                .addContainerGap(47, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(45, Short.MAX_VALUE)
                .addGap(43, 43, 43))

    }// </editor-fold>

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainJFrame().setVisible(true);

    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    // End of variables declaration

We can see that the form is a class which inherits from the JFrame class. This is the class representing the window. In the constructor, the strange initComponents() method with a collapsed code is called. Even if we expand it, NetBeans won't allow us to write to this part of the class.

The initComponents() method is automatically generated by NetBeans as you create your form in the designer. Even though it looks complicated, it does nothing but creates all the elements on the form and set their properties as we have chosen. We can see here how our label being created and its properties being set. The method is then called in the constructor to initialize the form. The programmer is therefore fully relieved from the code generated by the designer, mainly to avoid breaking it :) However, it's important to know how it works so that you are able to, for example, add controls at runtime.

Because Swing uses, like e.g. HTML, relative positions, NetBeans generates a lot of other invisible components, such as various spaces, separators, and layouts. We'll skip those in this course as we won't need them because of the graphic designer. However, these components are explained in detail in the Design by hand in Java Swing series, where the graphic designer is not used. So it's important that the programmer understands exactly how to place elements on the form because he must do it himself.

In the class, we can also find the main() method, which creates the form and sets its Look and Feel to it. Simply said, that's the form's skin. Nimbus is the default theme in NetBeans. You can change this value to Windows, so your application will then look like you're used to in Windows. At the end of the method, an instance of the main form is created. By default, the application window will appear in the upper left corner of the screen when it's launched. The user would expect it in the center and unfortunately, it can't be set in Properties. Therefore, we'll edit the form creation code and add a line to center it:

public void run() {
    MainJFrame mainJFrame = new MainJFrame();

When you run the application, the window will be in the middle of the screen.

At the very end of the file, you'll find the components that you added to the form. Note that their class name always starts with J, e.g. JLabel. This is to distinguish them from older AWT components and also because they are Java classes.

Today's project is available for download as an attachment to the article, including the source code. Next time, in the lesson Simple calculator in Java Swing, we'll explain how events work and program a simple calculator.



By downloading the following file, you agree to the license terms

Downloaded 268x (20.39 kB)


Previous article
Introduction to form applications in Java Swing
All articles in this section
Form Applications in Java Swing
Skip article
(not recommended)
Simple calculator in Java Swing
Article has been written for you by David Capka
User rating:
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn university David learned IT at the Unicorn University - a prestigious college providing education on IT and economics.