# Java Notes

# NetBeans Code Snippets

One of the very nice things about the NetBeans editor (and many other editors), is that they allow you to insert predefined blocks of code easily. This makes writing some wordy blocks of standard code very easy. Many IDEs refer to these little pieces of code as snippets, but NetBeans refers to them as templates. Here are some that I use frequently.

How to add them to NetBeans. You can copy and paste the sample code below into NetBeans.

1. Open `Tools` menu.
2. Choose `Options` menu item.
3. Click on the `Editor` icon in the left panel.
4. Choose the `Code Templates` tab.
5. Click the `New` button. In the dialog box enter the abbreviation you would like to use for this. Do not choose a word or variable name that you would normally type.
6. Enter the text of the code template in the text area.

## Comment header (xheader)

I put a fairly standard block of comments at the front of each file. Of course, you don't want to use my name, but something like this is handy. Typing `xheader`+space produces this:

      1
      2
      3
    // File       : xxx
    // Description: xxx
    // Author     : Your Name - 2007-mm-dd - Placed in public domain.

## Generic GUI program (xgui)

The following kcomplete GUI program can be inserted immediately after the header comments and optional package declaration. It is a very simple subclass of JFrame. You will have to add a lot to it, but this gives you a good starting point to prevent "blank screen" anxiety.

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;

    ///////////////////////////////////////////////////////////////////// ${Identifier}
    public class ${Identifier} extends JFrame {
        //================================================================ constants
        private static final String PROMPT = "Do you really want to quit?";

        //=================================================================== fields
        //... GUI components referenced by listeners, model refs, ....

        //============================================================== constructor
        public ${Identifier}() {
            //... Build components.
            JButton quitButton = new JButton("Quit");

            //... Add Listeners
            quitButton.addActionListener(new QuitAction());

            //... Create content pane, set layout and border.
            JPanel content = new JPanel();
            content.setLayout(new BorderLayout(5, 5));
            content.setBorder(BorderFactory.createEmptyBorder(12,12,12,12));
            content.add(quitButton);

            //... Set window attributes.
            super.setContentPane(content);
            super.pack();                               // Layout components.
            super.setTitle("${Identifier}");
            super.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            super.setLocationRelativeTo(null);          // Center window.
        }

        /////////////////////////////////////////// innner listener class QuitAction
        class QuitAction implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                int confirm = JOptionPane.showConfirmDialog(${Identifier}.this, PROMPT);
                if (confirm == JOptionPane.OK_OPTION) {
                    System.exit(0);
                }
            }
        }

        //===================================================================== main
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    ${Identifier} window = new ${Identifier}();
                    window.setVisible(true);
                }
            });
        }
    }

## Applet - Application (xappapp)

This produces most of the file (no header comments, package declaration, or imports) that is the skeleton of both an application and an applet.

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
    ////////////////////////////////////////////////////////////////// ${Identifier}
    public class ${Identifier} extends JApplet {
        //================================================================ constants

        //=================================================================== fields

        //===================================================================== main
        public static void main(String[] args) {
            //... Create and initialize the applet.
            JApplet theApplet = new ${Identifier}();

            //... Create a window (JFrame) and make applet the content pane.
            JFrame window = new JFrame("${Identifier}");
            window.setContentPane(theApplet);
            window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            window.pack();              // Arrange the components.
            //System.out.println(theApplet.getSize());
            window.setLocationRelativeTo(null);  // Center the window.
            window.setVisible(true);    // Make the window visible.
        }

        //============================================================== constructor
        public ${Identifier}() {
            //... Create Applet/content pane GUI here.
        }
    }

## Graphics class (xgraphics)

Often I need a subclass of JComponent to draw on. The following code template generates a basic class for graphics.

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
    import java.awt.*;
    import javax.swing.*;

    //////////////////////////////////////////////////////////// ${Identifier}
    public class ${Identifier} extends JComponent {

        //================================================================ constants
        private static final int   WIDTH  = 200;
        private static final int   HEIGHT = 200;
        private static final Color BACKGROUND_COLOR = Color.WHITE;

        //============================================================== constructor
        public ${Identifier}() {
            this.setPreferredSize(new Dimension(WIDTH, HEIGHT));
        }

        //=========================================================== paintComponent
        @Override public void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D)g;   // Downcast.

            //... Paint background.
            g2.setColor(BACKGROUND_COLOR);
            g2.fillRect(0, 0, getWidth(), getHeight());
            g2.setColor(Color.BLACK);        // Set pen to black.
        }
    }

## Add anonymous action listener (xaal)

Anonymous action listeners aren't always be the most general choice, but they are very convenient. Just type the button name, dot, then `xaal`+space.

      1
      2
      3
      4
      5
    addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ${cursor}
        }
    });

## Inner class listener (xicl)

One good way to implement a listener is to define an inner class that implements ActionListener. An inner class has access to the outer class's fields, so can get work with components defined in an outer JFrame subclass.

      1
      2
      3
      4
      5
      6
      7
      8
    ///////////////////////////////////////////////////////////////// ${Identifier}
    class ${Identifier} implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            //... Do something.
        }
    }