How do I set Swing Timer initial delay?

The Swing javax.swing.Timer object fires the action event after the delay time specified in the constructor passed. For some reasons you might want the Timer class fires immediately after it was started.

To achieve this you can set the timer initial delay by calling the setInitialDelay(int initialDelay) method. The example below give you an example how to do it.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class TimerInitialDelayDemo extends JFrame {
    private JLabel counterLabel = new JLabel();

    private Timer timer = null;

    public TimerInitialDelayDemo() throws HeadlessException {
        initUI();
    }

    private void initUI() {
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(200, 200);

        Container container = getContentPane();
        container.setLayout(new FlowLayout(FlowLayout.CENTER));
        container.add(counterLabel);

        timer = new Timer(1000, new MyActionListener());

        // Set initial delay of the Timer object. Setting initial delay
        // to zero causes the timer fires the event immediately after
        // it is started.
        timer.setInitialDelay(0);
        timer.start();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new TimerInitialDelayDemo().setVisible(true);
            }
        });
    }

    class MyActionListener implements ActionListener {
        private int counter = 10;

        public void actionPerformed(ActionEvent e) {
            counter = counter - 1;
            String text = "<html><font size=\"14\">" +
                String.valueOf(counter) +
                "</font></head>";
            counterLabel.setText(text);
            if (counter == 0) {
                timer.stop();
            }
        }
    }
}

How do I create a ButtonGroup for radio buttons?

This example shows you how to create a ButtonGroup for grouping our radio buttons components into a single group. In this example you can also see that we add an action listener to the radio buttons.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ButtonGroupDemo extends JFrame {
    public ButtonGroupDemo() {
        initializeUI();
    }

    private void initializeUI() {
        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        // Creating an action listener for our radio button.
        ActionListener action = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JRadioButton button = (JRadioButton) e.getSource();
                System.out.println("You select button: " + button.getText());
            }
        };

        // Creates four radio buttons and set the action listener.
        JRadioButton button1 = new JRadioButton("One");
        button1.addActionListener(action);
        JRadioButton button2 = new JRadioButton("Two");
        button2.addActionListener(action);
        JRadioButton button3 = new JRadioButton("Three");
        button3.addActionListener(action);
        JRadioButton button4 = new JRadioButton("Four");
        button4.addActionListener(action);

        // Create a ButtonGroup to group our radio buttons into one group. This
        // will make sure that only one item or one radio is selected on the
        // group.
        ButtonGroup group = new ButtonGroup();
        group.add(button1);
        group.add(button2);
        group.add(button3);
        group.add(button4);

        getContentPane().add(button1);
        getContentPane().add(button2);
        getContentPane().add(button3);
        getContentPane().add(button4);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ButtonGroupDemo().setVisible(true);
            }
        });
    }
}

How do I add an action listener to JComboBox?

The code below shows you how to add an ActionListener to a JComboBox component. In the snippet we add a listener by calling the addActionListener() method and give an instance of ActionListener listener as an anonymous class (a class without a specified name) as the parameter.

The ActionListener interface contract said that we must implement the actionPerformed(ActionEvent e) method. This is the place where the event will be handled by our program.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ComboBoxActionListener extends JFrame {
    public ComboBoxActionListener() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        String[] names = new String[]{
                "James", "Joshua", "Matt", "John", "Paul"
        };
        JComboBox comboBox = new JComboBox<String>(names);
        comboBox.setEditable(true);

        // Create an ActionListener for the JComboBox component.
        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent event) {
                // Get the source of the component, which is our combo
                // box.
                JComboBox comboBox = (JComboBox) event.getSource();

                // Print the selected items and the action command.
                Object selected = comboBox.getSelectedItem();
                System.out.println("Selected Item  = " + selected);
                String command = event.getActionCommand();
                System.out.println("Action Command = " + command);

                // Detect whether the action command is "comboBoxEdited"
                // or "comboBoxChanged"
                if ("comboBoxEdited".equals(command)) {
                    System.out.println("User has typed a string in " +
                            "the combo box.");
                } else if ("comboBoxChanged".equals(command)) {
                    System.out.println("User has selected an item " +
                            "from the combo box.");
                }
            }
        });
        getContentPane().add(comboBox);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ComboBoxActionListener().setVisible(true);
            }
        });
    }
}

How do I add items and remove items from JComboBox?

This example demonstrate how to add an items into a specific position in the combo box list or at the end of the list using the insertItemAt(Object o, int index) and addItem(Object o) method. In the code we also learn how to remove one or all items from the list using removeItemAt(int index) method and removeAllItems() method of JComboBox.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ComboBoxAddRemoveItem extends JFrame {
    public ComboBoxAddRemoveItem() {
        initialize();
    }

    private void initialize() {
        setSize(300, 300);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        String[] items = new String[] {"Two", "Four", "Six", "Eight"};
        final JComboBox comboBox = new JComboBox(items);

        getContentPane().add(comboBox);

        JButton button1 = new JButton("Add One");
        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Add item "One" at the beginning of the list.
                comboBox.insertItemAt("One", 0);
            }
        });
        JButton button2 = new JButton("Add Five and Nine");
        button2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Add item Five on the third index and Nine at the end of the
                // list.
                comboBox.insertItemAt("Five", 3);
                comboBox.addItem("Nine");
            }
        });

        getContentPane().add(button1);
        getContentPane().add(button2);

        JButton remove1 = new JButton("Remove Eight and Last");
        remove1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // Remove the Eight item and the last item from the list.
                comboBox.removeItemAt(5);
                comboBox.removeItemAt(comboBox.getItemCount() - 1);
            }
        });
        JButton remove2 = new JButton("Remove All");
        remove2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                comboBox.removeAllItems();
            }
        });

        getContentPane().add(remove1);
        getContentPane().add(remove2);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ComboBoxAddRemoveItem().setVisible(true);
            }
        });
    }
}