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.swing;

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

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

    private Timer timer = null;

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

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

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

        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();
    }

    class MyActionListener implements ActionListener {
        private int counter = 10;

        public void actionPerformed(ActionEvent e) {
            counter = counter - 1;
            String text = "<html><font size='14'>" +
                    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.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();
    }

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

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

        // Creating an action listener for our radio button.
        ActionListener action = 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);
    }
}

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.swing;

import javax.swing.*;
import java.awt.FlowLayout;

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

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

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

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

        // Create an ActionListener for the JComboBox component.
        comboBox.addActionListener(event -> {
            // Get the source of the component, which is our combo
            // box.
            JComboBox comboBox1 = (JComboBox) event.getSource();

            // Print the selected items and the action command.
            Object selected = comboBox1.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);
    }
}

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.swing;

import javax.swing.*;
import java.awt.*;

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

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

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

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

        getContentPane().add(comboBox);

        JButton button1 = new JButton("Add One");
        button1.addActionListener(e -> {
            // Add item "One" at the beginning of the list.
            comboBox.insertItemAt("One", 0);
        });

        JButton button2 = new JButton("Add Five and Nine");
        button2.addActionListener(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(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(e -> comboBox.removeAllItems());

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