How do I create a vertical JSlider?

To create a vertical JSlider set the orientation on the JSlider‘s constructor to JSlider.VERTICAL. If you do not pass JSlider.VERTICAL as a constructor parameter use the setOrientation() method instead.

package org.kodejava.swing;

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

public class JSliderVertical extends JPanel {
    public JSliderVertical() {
        initializeUI();
    }

    public static void showFrame() {
        JPanel panel = new JSliderVertical();
        panel.setOpaque(true);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setTitle("Vertical JSlider");
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(JSliderVertical::showFrame);
    }

    private void initializeUI() {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(500, 200));

        // Creates a vertical JSlider that accept value in the
        // range between 0 and 20. The initial value is set to 4.
        JSlider slider = new JSlider(JSlider.VERTICAL, 0, 20, 4);
        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        slider.setMinorTickSpacing(1);
        slider.setMajorTickSpacing(4);

        add(slider, BorderLayout.CENTER);
    }
}

The screen capture of the code snippet above.

Vertical JSlider Demo

How do I use a JSlider component?

This simple example show you how to use the JSlider component. A JSlider component is intended to let the user easily enter a numeric value bounded by a minimum and maximum value.

There are a couples properties that you need to set when creating a JSlider. These include setting setMinorTickSpacing(), setMajorTickSpacing(), setPaintTicks() and setPaintLabels(). These methods set the minor tick spacing, major tick spacing, display the ticks and the tick labels.

To get the selected value from JSlider we need to implements the stateChanged() method defined in the ChangeListener interface and then pass the listener to the JSlider by calling the addChangeListener() method.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;

public class JSliderDemo extends JPanel implements ChangeListener {
    private JTextField field;

    public JSliderDemo() {
        initializeUI();
    }

    private void initializeUI() {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(500, 200));

        // Creates an instance of JSlider with a horizontal
        // orientation. Define 0 as the minimal value and
        // 50 as the maximum value. The initial value is set
        // to 10.
        JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 10);

        slider.setPaintTicks(true);
        slider.setPaintLabels(true);
        slider.setMinorTickSpacing(1);
        slider.setMajorTickSpacing(10);

        slider.addChangeListener(this);

        JLabel label = new JLabel("Selected Value:");
        field = new JTextField(5);

        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout());
        panel.add(label);
        panel.add(field);

        add(slider, BorderLayout.NORTH);
        add(panel, BorderLayout.SOUTH);
    }

    public void stateChanged(ChangeEvent e) {
        JSlider slider = (JSlider) e.getSource();

        // Get the selection value of JSlider
        field.setText(String.valueOf(slider.getValue()));
    }

    public static void showFrame() {
        JPanel panel = new JSliderDemo();
        panel.setOpaque(true);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setTitle("JSlider Demo");
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JSliderDemo.showFrame();
            }
        });
    }
}

Below is the result of the code snippet above.

JSlider Demo

How do I create a scrollable JTable component?

To create a scrollable JTable component we have to use a JScrollPane as the container of the JTable. Besides, that we also need to set the table auto resize mode to JTable.AUTO_RESIZE_OFF so that a horizontal scroll bar displayed by the scroll pane when needed. If we do not turn off the auto resize mode, the columns of the table will be resized to fit the available window size.

package org.kodejava.swing;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;
import java.awt.Dimension;

public class ScrollableJTable extends JPanel {
    public ScrollableJTable() {
        initializeUI();
    }

    private static void showFrame() {
        JPanel panel = new ScrollableJTable();
        panel.setOpaque(true);

        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setTitle("Scrollable JTable");
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(ScrollableJTable::showFrame);
    }

    private void initializeUI() {
        setLayout(new BorderLayout());
        setPreferredSize(new Dimension(500, 250));

        JTable table = new JTable(20, 20);

        // Turn off JTable's auto resize so that JScrollPane will show a horizontal
        // scroll bar.
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        JScrollPane pane = new JScrollPane(table);
        add(pane, BorderLayout.CENTER);
    }
}

Below is the result of the code snippet above.

Scrollable JTable Component Demo

Scrollable JTable Component Demo

How do I throw exceptions in Java?

The exceptions that you catch in a try-catch block must have been raised by a method that you’ve called. You can raise an exception with a statement that consists of the throw keyword, followed by an exception object. This exception object is an instance of any subclass of the Throwable class.

In the example below we have two static methods that throws exception. The first method, throwException() will throw an ArithmethicException when the divider is a zero value integer. The second method, printDate(Date date) will throw a NullPointerException if the date parameter value is null.

package org.kodejava.basic;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ThrowExample {
    public static void main(String[] args) {
        try {
            ThrowExample.throwException();
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            ThrowExample.printDate(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void throwException() {
        int x = 6;
        int[] numbers = {3, 2, 1, 0};

        for (int y : numbers) {
            if (y == 0) {
                // Throws an ArithmeticException when about to
                // divide by zero.
                String message = String.format(
                        "x = %d; y = %d; a division by zero.",
                        x, y);
                throw new ArithmeticException(message);
            } else {
                int z = x / y;
                System.out.println("z = " + z);
            }
        }
    }

    public static void printDate(Date date) {
        if (date == null) {
            throw new NullPointerException("Date cannot be null.");
        }
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        System.out.println("Date: " + df.format(date));
    }
}

The output of our code:

z = 2
z = 3
z = 6
java.lang.ArithmeticException: x = 6; y = 0; a division by zero.
    at org.kodejava.basic.ThrowExample.throwException(ThrowExample.java:33)
    at org.kodejava.basic.ThrowExample.main(ThrowExample.java:10)
java.lang.NullPointerException: Date cannot be null.
    at org.kodejava.basic.ThrowExample.printDate(ThrowExample.java:43)
    at org.kodejava.basic.ThrowExample.main(ThrowExample.java:16)

How do I catch multiple exceptions?

If a try block can throw several kind of exceptions, and you want to handle each exception differently, you can put several catch blocks to handle it.

package org.kodejava.basic;

public class MultipleCatchExample {
    public static void main(String[] args) {
        int[] numbers1 = {1, 2, 3, 4, 5};
        int[] numbers2 = {1, 2, 3, 4, 5, 6};

        try {
            // This line throws an ArrayIndexOutOfBoundsException
            MultipleCatchExample.printResult(numbers1);

            // This line throws an ArithmeticException
            MultipleCatchExample.printResult(numbers2);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        } finally {
            System.out.println("Finally block is always executed.");
        }
    }

    /**
     * Divide the given first number by the second number.
     *
     * @param x the first number.
     * @param y the second number.
     * @return the result of division.
     */
    private static int divide(int x, int y) {
        return x / y;
    }

    /**
     * Print the output result of divide operation by calling the
     * divide() method.
     *
     * @param numbers integer arrays of the divided number
     * @throws ArrayIndexOutOfBoundsException when an exception
     *                                        occurs.
     */
    private static void printResult(int[] numbers) {
        int x, z, y = 1;
        for (int i = 0; i < 6; i++) {
            x = numbers[i];
            if (i == 5) {
                y = 0;
            }
            z = MultipleCatchExample.divide(x, y);
            System.out.println("z = " + z);
        }
    }
}