How do I change the number of visible items in JComboBox?

In this example you’ll see how we can change the default number of visible items in the combo box. By default, it only shows eight items at once and when the combo box has more items a scrollbar will be shown, so we can scroll up and down in the combo box list.

If we want to change this value we can call the setMaximumRowCount(int count) of the JComboBox. Let’s see the following example for more details.

package org.kodejava.swing;

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

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

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

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

        // Create some items for our JComboBox component. In this example we are
        // going to pass an array of string which are the name of the month.
        String[] months = {"January", "February", "March", "April", "Mei", "June",
                "July", "August", "September", "October", "November", "December"};

        // Create a month selection combo box.
        JComboBox<String> comboBox = new JComboBox<>(months);

        // By default, combo box will only show eight items in the drop-down. When
        // more than eight items are in the combo box a default scrollbar will be
        // shown. If we want to display more items we can change it by calling the
        // setMaximumRowCount() method.
        comboBox.setMaximumRowCount(12);

        getContentPane().add(comboBox);
    }
}

How do I create a table in PDF document in iText?

This example shows how to create a table in a PDF document. Using the iText PDF library we can use the PdfPTable and the PdfPCell classes to create table and cells in our PDF document. In the following example we use array of strings to define the table’s data.

Let’s see the complete code snippet below:

package org.kodejava.itextpdf;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;

public class TableDemo {
    public static void main(String[] args) {
        String[] headers = new String[]{"No", "Username", "First Name", "Last Name"};
        String[][] rows = new String[][]{
                {"1", "jdow", "John", "Dow"},
                {"2", "stiger", "Scott", "Tiger"},
                {"3", "fbar", "Foo", "Bar"}
        };

        // Create a new document.
        Document document = new Document(PageSize.LETTER.rotate());

        try {
            // Get an instance of PdfWriter and create a Table.pdf file
            // as an output.
            PdfWriter.getInstance(document, new FileOutputStream("TableDemo.pdf"));
            document.open();

            // Create an instance of PdfPTable. After that we transform
            // the header and rows array into a PdfPCell object. When
            // each table row is complete we have to call the
            // table.completeRow() method.
            //
            // For better presentation we also set the cell font name,
            // size and weight. And we also define the background fill
            // for the cell.
            Font fontHeader = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD);
            Font fontRow = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.NORMAL);

            PdfPTable table = new PdfPTable(headers.length);
            for (String header : headers) {
                PdfPCell cell = new PdfPCell();
                cell.setGrayFill(0.9f);
                cell.setPhrase(new Phrase(header.toUpperCase(), fontHeader));
                table.addCell(cell);
            }
            table.completeRow();

            for (String[] row : rows) {
                for (String data : row) {
                    Phrase phrase = new Phrase(data, fontRow);
                    table.addCell(new PdfPCell(phrase));
                }
                table.completeRow();
            }

            document.addTitle("PDF Table Demo");
            document.add(table);
        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
    }
}

Maven Dependencies

<dependency>
    <groupId>com.itextpdf</groupId>
    <artifactId>itextpdf</artifactId>
    <version>5.5.13.3</version>
</dependency>

Maven Central

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

How do I get items of JComboBox?

This example demonstrate the use of JComboBox‘s getItemCount() method and getItemAt(int index) to get the number of items inside the combo box and how to obtain each of them.

package org.kodejava.swing;

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

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

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

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

        // Create JComboBox with grade as the values;
        String[] items = new String[]{"A", "B", "C", "D", "E", "F"};
        final JComboBox<String> gradeCombo = new JComboBox<>(items);
        getContentPane().add(gradeCombo);

        JButton button = new JButton("Get Items");
        final JLabel label = new JLabel("Items count: ");

        button.addActionListener(e -> {
            // Get the number of items in the combo box drop-down. Iterate
            // from zero to the number of combo box items and get each item
            // of the specified index.
            //
            // In this example we just place the items inside a StringBuilder
            // and print it later on.
            int count = gradeCombo.getItemCount();
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < count; i++) {
                builder.append(gradeCombo.getItemAt(i));
                if (i < count - 1) {
                    builder.append(", ");
                }
            }
            label.setText("Item count: " + count + "; ["
                    + builder + "]");
        });

        getContentPane().add(button);
        getContentPane().add(label);
    }
}

How do I set and get the selected item in JComboBox?

The code below demonstrate how to set the selected item of JComboBox and then on how to get the value of the selected item. In this example we set the JComboBox component so that user can enter their own value.

package org.kodejava.swing;

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

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

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

    private void initialize() {
        setSize(500, 500);
        setTitle("JComboBox Selected Item");
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        // Create a combo box with four items and set it to editable so that 
        // user can
        // enter their own value.
        final JComboBox<String> comboBox = 
                new JComboBox<>(new String[]{"One", "Two", "Three", "Four"});
        comboBox.setEditable(true);
        getContentPane().add(comboBox);

        // Create two button that will set the selected item of the combo box. 
        // The first button select "Two" and second button select "Four".
        JButton button1 = new JButton("Set Two");
        getContentPane().add(button1);
        button1.addActionListener(e -> comboBox.setSelectedItem("Two"));

        JButton button2 = new JButton("Set Four");
        getContentPane().add(button2);
        button2.addActionListener(e -> comboBox.setSelectedItem("Four"));

        // Create a text field for displaying the selected item when we press 
        // the "Get Value" button. When user enter their own value the selected 
        // item returned is the string that entered by user.
        final JTextField textField = new JTextField("");
        textField.setPreferredSize(new Dimension(150, 20));

        JButton button3 = new JButton("Get Value");
        getContentPane().add(button3);
        getContentPane().add(textField);
        button3.addActionListener(
                e -> textField.setText((String) comboBox.getSelectedItem()));
    }
}