How do I do a conditional logging?

When logging some messages in our application the purpose could be creating a log for debugging purposes. To minimize the impact of these debug message we can use a conditional logging. To do this we need to wrap each call to the logger method with a Logger.isLoggable(Level level) check.

The check will ensure that only logs with the appropriate level will be logged into our application logs. This will automate the on and off our application log without touching the code.

package org.kodejava.util.logging;

import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.Date;

public class ConditionalLogging {
    private Logger logger =
            Logger.getLogger(ConditionalLogging.class.getName());

    public static void main(String[] args) {
        ConditionalLogging demo = new ConditionalLogging();
        demo.executeMethod();
    }

    // In this method we will check if the Logger level is equals to
    // Level.INFO before we do the real logging. This will minimize
    // the impact of logging if in the next time we increase the level
    // to Level.WARNING or Level.SEVERE so that these message will not
    // be logged anymore.
    public void executeMethod() {
        if (logger.isLoggable(Level.INFO)) {
            logger.info("Entering executeMethod() at : " + new Date());
        }

        // Method body
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                System.out.print(i * j + " ");
            }
            System.out.println();
        }

        if (logger.isLoggable(Level.INFO)) {
            logger.info("Exiting executeMethod() at  : " + new Date());
        }
    }
}

The result of our example code above is shown below:

Oct 07, 2021 8:26:49 PM org.kodejava.util.logging.ConditionalLogging executeMethod
INFO: Entering executeMethod() at : Thu Oct 07 20:26:49 CST 2021
Oct 07, 2021 8:26:49 PM org.kodejava.util.logging.ConditionalLogging executeMethod
INFO: Exiting executeMethod() at  : Thu Oct 07 20:26:49 CST 2021
0 0 0 0 0 
0 1 2 3 4 
0 2 4 6 8 
0 3 6 9 12 
0 4 8 12 16 

How do I log an exception?

In this example you can see how we can log an exception when it occurs. In the code below we are trying to parse an invalid date which will give us a ParseException. To log the exception we call the Logger.log() method, passes the logger Level, add some user-friendly message and the Throwable object.

package org.kodejava.util.logging;

import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;

public class LoggingException {
    private static Logger logger =
            Logger.getLogger(LoggingException.class.getName());

    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        df.setLenient(false);

        try {
            // Try to parse a wrong date.
            Date date = df.parse("12/30/1990");

            System.out.println("Date = " + date);
        } catch (ParseException e) {
            // Create a Level.SEVERE logging message
            if (logger.isLoggable(Level.SEVERE)) {
                logger.log(Level.SEVERE, "Error parsing date", e);
            }
        }
    }
}

The code above will produce the following log message.

Oct 07, 2021 8:21:44 PM org.kodejava.util.logging.LoggingException main
SEVERE: Error parsing date
java.text.ParseException: Unparseable date: "12/30/1990"
    at java.base/java.text.DateFormat.parse(DateFormat.java:399)
    at org.kodejava.util.logging.LoggingException.main(LoggingException.java:20)

How do I check if a message is loggable?

The Logger class provide a setLevel() method to set the logging level. By setting logging to a certain level we can control which message will be logged.

To determine or check if a message will be logged we can use the Logger.isLoggable(Level level) method. Let see the example below.

package org.kodejava.util.logging;

import java.util.logging.Logger;
import java.util.logging.Level;

public class LoggingLevelCheck {
    public static void main(String[] args) {
        // Obtains an instance of Logger and set the logging level to 
        // Level.WARNING.
        Logger log = Logger.getLogger(LoggingLevelCheck.class.getName());
        log.setLevel(Level.WARNING);

        // Log INFO level message. This message will not be logged due to
        // the log level set to Level.WARNING
        if (log.isLoggable(Level.INFO)) {
            log.info("Application Information Message");
        }

        // Log WARNING level message when Level.WARNING is loggable.
        if (log.isLoggable(Level.WARNING)) {
            log.warning("Application Warning Information");
        }

        // Log SEVERE level message when Level.SEVERE is loggable.
        if (log.isLoggable(Level.SEVERE)) {
            log.severe("Information Severe Information");
        }
    }
}

This will result only the Level.WARNING and Level.SEVERE messages are logged.

Oct 07, 2021 8:18:03 PM org.kodejava.util.logging.LoggingLevelCheck main
WARNING: Application Warning Information
Oct 07, 2021 8:18:03 PM org.kodejava.util.logging.LoggingLevelCheck main
SEVERE: Information Severe Information

How do I obtain or create a Logger?

Since JDK 1.4 a logging API was introduced into the Java class libraries. This API enables our application to logs some messages to record our application activities.

To create an instance of Logger we can call the Logger.getLogger() factory method which will return the available logger for the given namespace, or it will create a new one when it doesn’t exist.

package org.kodejava.util.logging;

import java.util.logging.Logger;

public class LoggingDemo {
    public static void main(String[] args) {
        // Obtaining an instance of Logger. This will create a new Logger
        // is it doesn't exist.
        Logger log = Logger.getLogger(LoggingDemo.class.getName());

        // Log some message using a different type of severity level.
        log.info("Info Message");
        log.warning("Warning Message");
        log.severe("Severe Message");
        log.config("Config Message");
        log.fine("Fine Message");
        log.finer("Finer Message");
        log.finest("Finest Message");
    }
}

After we create the Logger instance we can create a message log by calling the logging method such as info(String message), warning(String message) and severe(String message). Below are some message produces by the Logger.

Oct 07, 2021 8:13:48 PM org.kodejava.util.logging.LoggingDemo main
INFO: Info Message
Oct 07, 2021 8:13:48 PM org.kodejava.util.logging.LoggingDemo main
WARNING: Warning Message
Oct 07, 2021 8:13:48 PM org.kodejava.util.logging.LoggingDemo main
SEVERE: Severe Message

How do I create a compound border?

In this example we create a compound border, a border around border. Here, instead of creating a new instance of Border class directly we create the border using the BorderFactory factory class.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import javax.swing.border.Border;
import java.awt.*;

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

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

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

        BevelBorder raisedBevel =
                (BevelBorder) BorderFactory.createBevelBorder(BevelBorder.RAISED);
        BevelBorder loweredBevel =
                (BevelBorder) BorderFactory.createBevelBorder(BevelBorder.LOWERED);
        Border border = BorderFactory.createCompoundBorder(raisedBevel, loweredBevel);
        JPanel panel = new JPanel();
        panel.setBorder(border);

        setContentPane(panel);
    }
}

How do I add a title to a border?

This example shows you how to create a border that have a title in it. There is a special border class the TitledBorder that does this. We can define the justification of the title, left, centered or right justify. To do this we call the setTitleJustification() method. We can also set other attributes such as font or the title position.

package org.kodejava.swing;

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

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

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

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

        TitledBorder border = new TitledBorder(" Form Data ");
        border.setTitleJustification(TitledBorder.LEFT);
        border.setTitlePosition(TitledBorder.TOP);

        JPanel panel = new JPanel();
        panel.setBorder(border);
        panel.setLayout(new GridLayout(1, 2));

        JLabel usernameLabel = new JLabel("Username: ");
        JTextField usernameField = new JTextField();
        panel.add(usernameLabel);
        panel.add(usernameField);

        setContentPane(panel);
    }
}

How do I create Border for swing component?

This example shows how we can create border for swing components. In the example below we set border of a JPanel component. Some border implementation that we use below including LineBorder, BevelBorder, EtchedBorder and MatteBorder.

package org.kodejava.swing;

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.border.BevelBorder;
import javax.swing.border.EtchedBorder;
import javax.swing.border.MatteBorder;
import java.awt.*;

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

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

    private void initializeUI() {
        setSize(400, 400);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new BorderLayout(15, 15));

        JPanel top = new JPanel();
        top.setBorder(new LineBorder(Color.RED, 1, true));

        JPanel bottom = new JPanel();
        bottom.setBorder(new BevelBorder(BevelBorder.LOWERED));

        JPanel left = new JPanel();
        left.setBorder(new EtchedBorder(EtchedBorder.RAISED));

        JPanel right = new JPanel();
        right.setBorder(new MatteBorder(5, 5, 5, 5, Color.BLUE));

        JPanel center = new JPanel();
        center.setBorder(new BevelBorder(BevelBorder.RAISED));

        getContentPane().add(top, BorderLayout.NORTH);
        getContentPane().add(bottom, BorderLayout.SOUTH);
        getContentPane().add(left, BorderLayout.WEST);
        getContentPane().add(right, BorderLayout.EAST);
        getContentPane().add(center, BorderLayout.CENTER);
    }
}

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 create JRadioButton and define some action?

Below we create a JRadioButton and pass an action handle to the component so that we know when the component is clicked.

package org.kodejava.swing;

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

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

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

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

        Action action = new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                JRadioButton button = (JRadioButton) e.getSource();
                System.out.println("actionPerformed " + button.getText());
            }
        };

        // Create a radio button and pass an AbstractAction as its constructor.
        // The action will be call everytime the radio button is clicked or
        // pressed. But when it selected programmatically the action will not 
        // be called.
        JRadioButton button = new JRadioButton(action);
        button.setText("Click Me!");
        button.setSelected(true);

        getContentPane().add(button);
    }
}

How do I create a JRadioButton component?

This simple example shows you how to create a JRadioButton component. To create an instance of JRadioButton we can simply call its constructor and pass a string as the radio button text.

We can also call the constructor with a boolean value after the text to indicate whether the radio button is selected or not.

package org.kodejava.swing;

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

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

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

    private void initializeUI() {
        setSize(500, 500);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setLayout(new GridLayout(1, 2));

        JPanel leftPanel = new JPanel();
        JLabel label = new JLabel("Employees: ");
        leftPanel.add(label);

        JPanel rightPanel = new JPanel(new GridLayout(4, 1));

        // Create a JRadioButton by calling the JRadioButton constructors and
        // passing a string for radio button text. We can also pass a boolean
        // value to select or unselect the radio button.
        JRadioButton radio1 = new JRadioButton("1 - 10");
        JRadioButton radio2 = new JRadioButton("11 - 50", true);
        JRadioButton radio3 = new JRadioButton("51 - 100");
        JRadioButton radio4 = new JRadioButton("101 - 1000", false);

        rightPanel.add(radio1);
        rightPanel.add(radio2);
        rightPanel.add(radio3);
        rightPanel.add(radio4);

        getContentPane().add(leftPanel);
        getContentPane().add(rightPanel);

        pack();
    }
}