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
MainJFrame.java
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() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jLabel1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Greetings"); jLabel1.setText("Greetings from the form"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(41, 41, 41) .addComponent(jLabel1) .addContainerGap(47, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(45, Short.MAX_VALUE) .addComponent(jLabel1) .addGap(43, 43, 43)) ); pack(); }// </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 http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } 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); } //</editor-fold> /* 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(); mainJFrame.setLocationRelativeTo(null); mainJFrame.setVisible(true); }
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.
Download
By downloading the following file, you agree to the license termsDownloaded 348x (20.39 kB)