Java - Light And Dark Mode Switcher

How to Create a Light Dark Mode Switcher with FlatLaf In Java Netbeans

Light And Dark Mode Switcher In Java




In this Java Tutorial we will see How To Create a JFrame with a toggle button for switching between light and dark modes. 
The application uses the FlatLaf library to provide a modern look and feel for Swing components.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.
- FlatLaf Library.





Project Source Code:


package new_tutorials;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import com.formdev.flatlaf.FlatDarculaLaf;
import com.formdev.flatlaf.FlatLightLaf;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

/**
 *
 * @author 1BestCsharp
 * download flatlaf - https://search.maven.org/artifact/com.formdev/flatlaf/3.2.5/jar?eh=
 */
public class LightDarkModeFrame extends JFrame{

    private JToggleButton darkLightToggle;
    
    public LightDarkModeFrame(){
        setTitle("Light Dark Mode Frame");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400,300);
        setLocationRelativeTo(null);
        
        intializeUI();
    }
    
    private void intializeUI(){
        
        JPanel panel = new JPanel();
        darkLightToggle = new JToggleButton("Dark Mode");
        
        darkLightToggle.addItemListener((e) -> {
            if(darkLightToggle.isSelected()){
                setDarkMode();
            }
            else{ setLightMode(); }
        });
        
        panel.add(darkLightToggle);
        panel.add(new JButton("Button"));
        panel.add(new JTextField(15));
        add(panel);
        
        setLightMode();
        
        darkLightToggle.setSelected(false);
        
    }
    
    private void setDarkMode(){
        try{
            UIManager.setLookAndFeel(new FlatDarculaLaf());
            darkLightToggle.setText("Light Mode");
            SwingUtilities.updateComponentTreeUI(this);
        }
        catch(Exception ex){ System.out.println(ex.getMessage()); }
    }
    
        private void setLightMode(){
        try{
            UIManager.setLookAndFeel(new FlatLightLaf());
            darkLightToggle.setText("Dark Mode");
            SwingUtilities.updateComponentTreeUI(this);
        }
        catch(Exception ex){ System.out.println(ex.getMessage()); }
    }
        
    
    public static void main(String[] args) {
        LightDarkModeFrame frame = new LightDarkModeFrame();
        frame.setVisible(true);
    }
    
    
}


The Final Result:

toggle button for switching between light and dark modes in java








Share this

Related Posts

Previous
Next Post »