Source code snippets (examples)

This is a list of Alvin Alexander's source code snippets (simple source code examples).

A Java JFileChooser example, with ActionEvent, ActionListener, Insets, actionPerformed, showOpenDialog

This is a Java JFileChooser example from Sun Microsystems that shows how to work with a JFileChooser, and also shows related features, including ActionEvent, ActionListener, the actionPerformed and showOpenDialog methods, and more.

(I’ve included it here because I work with Java Swing applications quite a bit, and I want it to be easier to find on my website.)

/**
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */

import java.awt.BorderLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

/**
 * SwingFileChooserDemo.java is a 1.4 application that uses these files:
 * images/Open16.gif images/Save16.gif
 */
public class SwingFileChooserDemo extends JPanel implements ActionListener {
  static private final String newline = "\n";

  JButton openButton, saveButton;

  JTextArea log;

  JFileChooser fc;

  public SwingFileChooserDemo() {
    super(new BorderLayout());

    //Create the log first, because the action listeners
    //need to refer to it.
    log = new JTextArea(5, 20);
    log.setMargin(new Insets(5, 5, 5, 5));
    log.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(log);

    //Create a file chooser
    fc = new JFileChooser();

    //Uncomment one of the following lines to try a different
    //file selection mode. The first allows just directories
    //to be selected (and, at least in the Java look and feel,
    //shown). The second allows both files and directories
    //to be selected. If you leave these lines commented out,
    //then the default mode (FILES_ONLY) will be used.
    //
    //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    //fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    //Create the open button. We use the image from the JLF
    //Graphics Repository (but we extracted it from the jar).
    openButton = new JButton("Open a File...",
        createImageIcon("images/Open16.gif"));
    openButton.addActionListener(this);

    //Create the save button. We use the image from the JLF
    //Graphics Repository (but we extracted it from the jar).
    saveButton = new JButton("Save a File...",
        createImageIcon("images/Save16.gif"));
    saveButton.addActionListener(this);

    //For layout purposes, put the buttons in a separate panel
    JPanel buttonPanel = new JPanel(); //use FlowLayout
    buttonPanel.add(openButton);
    buttonPanel.add(saveButton);

    //Add the buttons and the log to this panel.
    add(buttonPanel, BorderLayout.PAGE_START);
    add(logScrollPane, BorderLayout.CENTER);
  }

  public void actionPerformed(ActionEvent e) {

    //Handle open button action.
    if (e.getSource() == openButton) {
      int returnVal = fc.showOpenDialog(SwingFileChooserDemo.this);

      if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        //This is where a real application would open the file.
        log.append("Opening: " + file.getName() + "." + newline);
      } else {
        log.append("Open command cancelled by user." + newline);
      }
      log.setCaretPosition(log.getDocument().getLength());

      //Handle save button action.
    } else if (e.getSource() == saveButton) {
      int returnVal = fc.showSaveDialog(SwingFileChooserDemo.this);
      if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        //This is where a real application would save the file.
        log.append("Saving: " + file.getName() + "." + newline);
      } else {
        log.append("Save command cancelled by user." + newline);
      }
      log.setCaretPosition(log.getDocument().getLength());
    }
  }

  /** Returns an ImageIcon, or null if the path was invalid. */
  protected static ImageIcon createImageIcon(String path) {
    java.net.URL imgURL = SwingFileChooserDemo.class.getResource(path);
    if (imgURL != null) {
      return new ImageIcon(imgURL);
    } else {
      System.err.println("Couldn't find file: " + path);
      return null;
    }
  }

  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    JDialog.setDefaultLookAndFeelDecorated(true);

    //Create and set up the window.
    JFrame frame = new JFrame("SwingFileChooserDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create and set up the content pane.
    JComponent newContentPane = new SwingFileChooserDemo();
    newContentPane.setOpaque(true); //content panes must be opaque
    frame.setContentPane(newContentPane);

    //Display the window.
    frame.pack();
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}

A Java JList example: DefaultListModel, ListSelectionModel, ListSelectionListener, and ActionListener

This is a Java JList example from Sun Microsystems that shows how to work with a JList, including some of the most common and important features, including DefaultListModel, ListSelectionModel, ListSelectionListener, ActionListener, and more. I’ve included it here because I work with Java Swing applications quite a bit, and I want it to be easier to find on my website.

/**
 * Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Sun Microsystems nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

// ListDemo.java requires no other files.
public class ListDemo extends JPanel implements ListSelectionListener {
  private JList list;
  private DefaultListModel listModel;

  private static final String hireString = "Hire";
  private static final String fireString = "Fire";
  private JButton fireButton;
  private JTextField employeeName;

  public ListDemo() {
    super(new BorderLayout());

    listModel = new DefaultListModel();
    listModel.addElement("Debbie Scott");
    listModel.addElement("Scott Hommel");
    listModel.addElement("Sharon Zakhour");

    // Create the list and put it in a scroll pane.
    list = new JList(listModel);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setSelectedIndex(0);
    list.addListSelectionListener(this);
    list.setVisibleRowCount(5);
    JScrollPane listScrollPane = new JScrollPane(list);

    JButton hireButton = new JButton(hireString);
    HireListener hireListener = new HireListener(hireButton);
    hireButton.setActionCommand(hireString);
    hireButton.addActionListener(hireListener);
    hireButton.setEnabled(false);

    fireButton = new JButton(fireString);
    fireButton.setActionCommand(fireString);
    fireButton.addActionListener(new FireListener());

    employeeName = new JTextField(10);
    employeeName.addActionListener(hireListener);
    employeeName.getDocument().addDocumentListener(hireListener);
    String name = listModel.getElementAt(list.getSelectedIndex()).toString();

    // Create a panel that uses BoxLayout.
    JPanel buttonPane = new JPanel();
    buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
    buttonPane.add(fireButton);
    buttonPane.add(Box.createHorizontalStrut(5));
    buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
    buttonPane.add(Box.createHorizontalStrut(5));
    buttonPane.add(employeeName);
    buttonPane.add(hireButton);
    buttonPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));

    add(listScrollPane, BorderLayout.CENTER);
    add(buttonPane, BorderLayout.PAGE_END);
  }

  class FireListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      // This method can be called only if
      // there's a valid selection
      // so go ahead and remove whatever's selected.
      int index = list.getSelectedIndex();
      listModel.remove(index);

      int size = listModel.getSize();

      if (size == 0) { // Nobody's left, disable firing.
        fireButton.setEnabled(false);

      } else { // Select an index.
        if (index == listModel.getSize()) {
          // removed item in last position
          index--;
        }

        list.setSelectedIndex(index);
        list.ensureIndexIsVisible(index);
      }
    }
  }

  // This listener is shared by the text field and the hire button.
  class HireListener implements ActionListener, DocumentListener {
    private boolean alreadyEnabled = false;
    private JButton button;

    public HireListener(JButton button) {
      this.button = button;
    }

    // Required by ActionListener.
    public void actionPerformed(ActionEvent e) {
      String name = employeeName.getText();

      // User didn't type in a unique name...
      if (name.equals("") || alreadyInList(name)) {
        Toolkit.getDefaultToolkit().beep();
        employeeName.requestFocusInWindow();
        employeeName.selectAll();
        return;
      }

      int index = list.getSelectedIndex(); // get selected index
      if (index == -1) { // no selection, so insert at beginning
        index = 0;
      } else { // add after the selected item
        index++;
      }

      listModel.insertElementAt(employeeName.getText(), index);
      // If we just wanted to add to the end, we'd do this:
      // listModel.addElement(employeeName.getText());

      // Reset the text field.
      employeeName.requestFocusInWindow();
      employeeName.setText("");

      // Select the new item and make it visible.
      list.setSelectedIndex(index);
      list.ensureIndexIsVisible(index);
    }

    // This method tests for string equality. You could certainly
    // get more sophisticated about the algorithm. For example,
    // you might want to ignore white space and capitalization.
    protected boolean alreadyInList(String name) {
      return listModel.contains(name);
    }

    // Required by DocumentListener.
    public void insertUpdate(DocumentEvent e) {
      enableButton();
    }

    // Required by DocumentListener.
    public void removeUpdate(DocumentEvent e) {
      handleEmptyTextField(e);
    }

    // Required by DocumentListener.
    public void changedUpdate(DocumentEvent e) {
      if (!handleEmptyTextField(e)) {
        enableButton();
      }
    }

    private void enableButton() {
      if (!alreadyEnabled) {
        button.setEnabled(true);
      }
    }

    private boolean handleEmptyTextField(DocumentEvent e) {
      if (e.getDocument().getLength() <= 0) {
        button.setEnabled(false);
        alreadyEnabled = false;
        return true;
      }
      return false;
    }
  }

  // This method is required by ListSelectionListener.
  public void valueChanged(ListSelectionEvent e) {
    if (e.getValueIsAdjusting() == false) {

      if (list.getSelectedIndex() == -1) {
        // No selection, disable fire button.
        fireButton.setEnabled(false);

      } else {
        // Selection, enable the fire button.
        fireButton.setEnabled(true);
      }
    }
  }

  /**
   * Create the GUI and show it. For thread safety, this method should be
   * invoked from the event-dispatching thread.
   */
  private static void createAndShowGUI() {
    // Create and set up the window.
    JFrame frame = new JFrame("ListDemo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // Create and set up the content pane.
    JComponent newContentPane = new ListDemo();
    newContentPane.setOpaque(true); // content panes must be opaque
    frame.setContentPane(newContentPane);

    // Display the window.
    frame.pack();
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        createAndShowGUI();
      }
    });
  }
}

A Java JCheckBox example with ItemEvent, ItemListener, setMnemonic, addItemListener, itemStateChanged

This is a Java JCheckBox example from Sun Microsystems that shows how to work with a JCheckBox, also showing other features, including ItemEvent, ItemListener, setMnemonic, addItemListener, and more.

(I’ve included it here because I work with Java Swing applications quite a bit, and I want it to be easier to find on my website.)

/**
 * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * -Redistribution of source code must retain the above copyright notice, this
 *  list of conditions and the following disclaimer.
 *
 * -Redistribution in binary form must reproduce the above copyright notice,
 *  this list of conditions and the following disclaimer in the documentation
 *  and/or other materials provided with the distribution.
 *
 * Neither the name of Sun Microsystems, Inc. or the names of contributors may
 * be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * This software is provided "AS IS," without a warranty of any kind. ALL
 * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
 * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
 * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
 * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
 * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
 * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
 * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
 * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
 * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
 * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 *
 * You acknowledge that this software is not designed, licensed or intended
 * for use in the design, construction, operation or maintenance of any
 * nuclear facility.
 */

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

/**
 * SwingCheckBoxDemo.java is a 1.4 application that requires 16 image files
 * in the images/geek directory: 
 * geek-----.gif, geek-c---.gif, geek--g--.gif, geek---h-.gif, geek----t.gif,
 * geek-cg--.gif, ..., geek-cght.gif.
 */
public class SwingCheckBoxDemo extends JPanel
                          implements ItemListener {
    JCheckBox chinButton;
    JCheckBox glassesButton;
    JCheckBox hairButton;
    JCheckBox teethButton;

    /**
     * Four accessory choices provide for 16 different
     * combinations. The image for each combination is
     * contained in a separate image file whose name indicates
     * the accessories. The filenames are "geek-XXXX.gif"
     * where XXXX can be one of the following 16 choices.
     * The "choices" StringBuffer contains the string that
     * indicates the current selection and is used to generate
     * the file name of the image to display.

       ----             //zero accessories

       c---             //one accessory
       -g--
       --h-
       ---t

       cg--             //two accessories
       c-h-
       c--t
       -gh-
       -g-t
       --ht

       -ght             //three accessories
       c-ht
       cg-t
       cgh-

       cght             //all accessories
     */

    StringBuffer choices;
    JLabel pictureLabel;

    public SwingCheckBoxDemo() {
        super(new BorderLayout());

        //Create the check boxes.
        chinButton = new JCheckBox("Chin");
        chinButton.setMnemonic(KeyEvent.VK_C);
        chinButton.setSelected(true);

        glassesButton = new JCheckBox("Glasses");
        glassesButton.setMnemonic(KeyEvent.VK_G);
        glassesButton.setSelected(true);

        hairButton = new JCheckBox("Hair");
        hairButton.setMnemonic(KeyEvent.VK_H);
        hairButton.setSelected(true);

        teethButton = new JCheckBox("Teeth");
        teethButton.setMnemonic(KeyEvent.VK_T);
        teethButton.setSelected(true);

        //Register a listener for the check boxes.
        chinButton.addItemListener(this);
        glassesButton.addItemListener(this);
        hairButton.addItemListener(this);
        teethButton.addItemListener(this);

        //Indicates what's on the geek.
        choices = new StringBuffer("cght");

        //Set up the picture label
        pictureLabel = new JLabel();
        pictureLabel.setFont(pictureLabel.getFont().deriveFont(Font.ITALIC));
        updatePicture();

        //Put the check boxes in a column in a panel
        
        JPanel checkPanel = new JPanel(new GridLayout(0, 1));
        checkPanel.add(chinButton);
        checkPanel.add(glassesButton);
        checkPanel.add(hairButton);
        checkPanel.add(teethButton);

        add(checkPanel, BorderLayout.LINE_START);
        add(pictureLabel, BorderLayout.CENTER);
        setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
    }

    /** Listens to the check boxes. */
    public void itemStateChanged(ItemEvent e) {
        int index = 0;
        char c = '-';
        Object source = e.getItemSelectable();

        if (source == chinButton) {
            index = 0;
            c = 'c';
        } else if (source == glassesButton) {
            index = 1;
            c = 'g';
        } else if (source == hairButton) {
            index = 2;
            c = 'h';
        } else if (source == teethButton) {
            index = 3;
            c = 't';
        }

        //Now that we know which button was pushed, find out
        //whether it was selected or deselected.
        if (e.getStateChange() == ItemEvent.DESELECTED) {
            c = '-';
        }

        //Apply the change to the string.
        choices.setCharAt(index, c);

        updatePicture();
    }

    protected void updatePicture() {
        //Get the icon corresponding to the image.
        ImageIcon icon = createImageIcon(
                                    "images/geek/geek-"
                                    + choices.toString()
                                    + ".gif");
        pictureLabel.setIcon(icon);
        pictureLabel.setToolTipText(choices.toString());
        if (icon == null) {
            pictureLabel.setText("Missing Image");
        } else {
            pictureLabel.setText(null);
        }
    }

    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
        java.net.URL imgURL = SwingCheckBoxDemo.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);

        //Create and set up the window.
        JFrame frame = new JFrame("SwingCheckBoxDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        JComponent newContentPane = new SwingCheckBoxDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}

How to create a custom JTabbedPane to manage tab title text font colors

This source code shows how to create a custom JTabbedPane to help you set the foreground color of a tab’s title text:

/**
 * With Java 7 and OS X 10.9 (and maybe 10.10), there is no visual distinction between
 * a tab that's enabled and one that is disabled, so this is an effort to fix that.
 */
class CustomTabbedPane extends JTabbedPane {

    var tftTabIsEnabled = false

    override def getForegroundAt(index: Int): Color = {
        if (index == 1) {
            if (tftTabIsEnabled) {
                setToolTipTextAt(1, "")
                super.getForegroundAt(index)
            } else {
                setToolTipTextAt(1, "Tab is disabled until you connect to a database and select a template directory")
                Color.GRAY
            }
        } else {
            super.getForegroundAt(index)
        }
    }

}

In this example, I wanted the second tab (index = 1) to be disabled by default, so I wrote the code as shown, then used my CustomTabbedPane class instead of the JTabbedPane. Other code in my project handled the process of knowing whether the tab should be enabled or disabled, and called this code as necessary in that process. I deleted that code so I don’t remember exactly how it worked, but it called invalidate() or updateUI() on the tabbed pane whenever the state changed.

The code here is written in Scala, but as you can see, it transfers easily to Java.

Java JComboBox - creating, adding a model, listening to item changes (user selections)

The following source code snippet shows how to create a JComboBox, set a simple DefaultComboBoxModel on it, and most importantly, add an ItemListener to it so your code can react to users changing the selection in the combobox.

The source code is written in Scala, but as you can see, it converts easily to Java:

// create a jcombobox
val languagesComboBox = new JComboBox

// give it a simple model
val languagesModel = new DefaultComboBoxModel(Array("Java", "JSON", "PHP", "Play", "Python"))
languagesComboBox.setModel(languagesModel)

This next source code example how to create a listener for the JComboBox, in this case an ItemListener:

// handle the case where the user changes the item selection in the jcombobox
val itemListener = new ItemListener {
    def itemStateChanged(itemEvent: ItemEvent) {
        val state = itemEvent.getStateChange
        if (state == ItemEvent.SELECTED) {
            val item = itemEvent.getItem.toString  // "Java", "JSON", etc.
            // now you can do something with the `item`, which is a String
        }
    }
}

As the comment shows, all you have to do in the itemStateChanged method is handle the item, which is the String that’s currently showing in the JComboBox.

Note that you do need to check that the state is equal to ItemEvent.SELECTED; each time a JComboBox selection is changed, two events are fired, one for the item that is de-selected, and one for the new item that is selected, and you generally just want one of those, i.e., the selected event, as shown.

How to put a JTextArea in a JScrollPane, set the font and margin, and set the scrollbars

I use this following Scala source code to create a Java JTextArea component, set its font, make it readonly, set its margin (insets), then put the textarea into a JScrollPane:

// text area
val textArea = new JTextArea(textAreaRows, textAreaColumns)
textArea.setFont(new Font("Helvetica Neue", Font.PLAIN, 20))
textArea.setEditable(false)
textArea.setMargin(new Insets(12, 12, 12, 12))
textArea.setText(textToDisplay)

// scrollpane
val scrollPane = new JScrollPane(textArea)
scrollPane.setPreferredSize(windowSize)
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS)
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS)

While the code is written in Scala, it converts easily to Java, as you can see. If you wanted to see any combination of setting a JTextArea in a JScrollPane, setting the textarea font or margins, setting the scrollpane size and/or controlling the scrollbars, I hope this is helpful.

How to set the font, caret position, and margins (insets) on a JTextArea component

The following source code shows how to set the font, caret position, and margins on a JTextArea component:

JTextArea textArea = new JTextArea();

// somewhere later in your code ...
textArea.setFont(new Font("Monaco", Font.PLAIN, 12));
textArea.setMargin(new Insets(12, 12, 12, 12));

textArea.setCaretPosition(0);

The Font and margin/insets probably make sense in terms of what they do.

The reason I set the caret position at position zero is in case the textarea gets filled with a lot of content; in that situation it will scroll the textarea to the bottom, and setting the caret position at 0 makes sure the beginning of the text is shown at the beginning of the JTextArea. One note about this: you probably have to set that caret position after you set the actual text (String) in the textarea. It’s been a while since I wrote this, but I think that’s true.

A Java method to copy text to the operating system clipboard

Here’s some source code for a Java method that lets you copy text (a String) to the clipboard on your operating system:

public void writeToClipboard(String s, ClipboardOwner owner) {
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    Transferable transferable = new StringSelection(s);
    clipboard.setContents(transferable, owner);
}

Don’t worry about that ClipboardOwner reference too much; you can just set it to null when calling this method, like this:

writeToClipboard(textArea.getText(), null);

If you wanted to see how to write a string to the clipboard in Java, I hope this example and source code is helpful.

A Java JTable row striping cell renderer

I just found the following source code that shows how to add row striping colors to a Java JTable.

package com.devdaily.heidi;

import java.awt.Color;
import java.awt.Component;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;

/**
 * I finally got this to work by implementing the checkbox renderer as shown below,
 * but in the end I'm not sure I like the look.
 */
public class StripedRowTableCellRenderer extends DefaultTableCellRenderer
{

  // i didn't like this color
  //private static final Color STRIPE = UIManager.getColor("textHighlight");
 
  // choose whatever color you prefer
  private static final Color STRIPE = new Color(0.929f, 0.953f, 0.996f);
  private static final Color WHITE = UIManager.getColor("Table.background");
 
  private final JCheckBox ckb = new JCheckBox();
 
  public StripedRowTableCellRenderer() {
    setOpaque(true); //MUST do this for background to show up.
  }

  public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
  {
    JComponent c = (JComponent)super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    
    if (!isSelected)
    {
      if (row % 2 == 0)
      {
        c.setBackground(WHITE);
      }
      else
      {
        c.setBackground(STRIPE);
      }
    }
    
    if (value instanceof Boolean) { // Boolean
      ckb.setSelected(((Boolean) value));
      ckb.setHorizontalAlignment(JLabel.CENTER);
      ckb.setBackground(super.getBackground());
      if (isSelected || hasFocus) {
          ckb.setBackground(table.getSelectionBackground());
      }
      return ckb;
    }
    
    
    return c;
  }

}

That code will alternate the JTable background colors for each row. That is, even number rows will have one color, and odd number rows will have a different background color.

Applying the JTable cell renderer

To use this class, you need to create an instance of it and then make it the cell renderer for the different objects that are shown in your JTable, something like this:

soundsTable.setDefaultRenderer(Object.class, new StripedRowTableCellRenderer());
soundsTable.setDefaultRenderer(Boolean.class, new StripedRowTableCellRenderer());

(For my own reference, so I can find all of the related source code, I used this code in my original Hyde project, and these last two lines of code are in a file named SoundFileController.java in that project.)

A Java Mac OS X "show file dialog" method

The following code is a “show file dialog” method that works on Mac OS X. I wrote the code a long time ago, but this still looks like the preferred way to show a file-chooser dialog on OS X, as of Java 7 and Mac OS X 10.9 and 10.10.

Here’s the Java source code:

/**
 * @param frame - parent frame
 * @param dialogTitle - dialog title
 * @param defaultDirectory - default directory
 * @param fileType - something like "*.jpg"
 * @return Returns null if the user selected nothing, otherwise returns the canonical filename (directory + fileSep + filename).
 */
String showFileDialog (Frame frame, String dialogTitle, String defaultDirectory, String fileType)
{
    FileDialog fd = new FileDialog(frame, dialogTitle, FileDialog.LOAD);
    fd.setFile(fileType);
    fd.setDirectory(defaultDirectory);
    fd.setLocationRelativeTo(frame);
    fd.setVisible(true);
    String directory = fd.getDirectory();
    String filename = fd.getFile();
    if (directory == null || filename == null || directory.trim().equals("") || filename.trim().equals(""))
    {
        return null;
    }
    else
    {
        // this was not needed on mac os x:
        //return directory + System.getProperty("file.separator") + filename;
        return directory + filename;
    }
}