Java - Switch Between Grid And List View

How to Create a Grid And List View Toggle In Java Netbeans

How to Create a Grid And List View Toggle In Java Netbeans




In this Java Tutorial we will see How To Create a custom-styled buttons to toggle between grid and list views In Java Using Netbeans.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:



/**
 *
 * @author 1BestCsharp
 */
public class ViewSwitcher extends JFrame {

    
    // Main panels for our application
    private JPanel mainPanel;           // The main container panel
    private JPanel contentPanel;        // Panel that holds our switchable views
    private CardLayout cardLayout;      // Layout manager for switching views
    
    // Our custom toggle buttons
    private ViewToggleButton gridButton;
    private ViewToggleButton listButton;
    
    // The two different view panels
    private JPanel gridViewPanel;
    private JPanel listViewPanel;
    
    // Color scheme
    private static final Color BACKGROUND_COLOR = new Color(245, 245, 247);  // Light gray background
    private static final Color ACCENT_COLOR = new Color(79, 70, 229);        // Indigo for active state
    private static final Color INACTIVE_COLOR = new Color(156, 163, 175);     // Gray for inactive state
    private static final Color HOVER_COLOR = new Color(99, 102, 241);        // Lighter indigo for hover
    
    public ViewSwitcher(){
        // Basic window setup
        setTitle("View Switcher");
        setSize(800, 600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  // Close app when window closes
        
        // Create the main panel that will hold everything
        mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBackground(BACKGROUND_COLOR);
        
        // Create the toggle buttons at the top
        JPanel togglePanel = createTogglePanel();
        mainPanel.add(togglePanel, BorderLayout.NORTH);
        
        // Create the content area that switches between views
        createContentPanels();
        
        // Add our main panel to the window and center it on screen
        add(mainPanel);
        setLocationRelativeTo(null);  // Centers the window
    }
    
    
    /**
     * Creates the panel containing our view toggle buttons
     * This panel appears at the top of the application
     */
    private JPanel createTogglePanel() {
        // Main panel for the toggle area
        JPanel panel = new JPanel();
        panel.setLayout(new FlowLayout(FlowLayout.RIGHT));  // Buttons aligned to the right
        panel.setBackground(BACKGROUND_COLOR);
        panel.setBorder(new EmptyBorder(15, 20, 15, 20));   // Add padding around the panel
        
        // Create a rounded container for our toggle buttons
        JPanel toggleGroup = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                // Custom painting to create rounded background
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                        RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(new Color(229, 231, 235));  // Light gray background
                g2.fill(new RoundRectangle2D.Double(0, 0, getWidth(), getHeight(), 12, 12));
                g2.dispose();
            }
        };
        
        
        toggleGroup.setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));  // No gaps between buttons
        toggleGroup.setOpaque(false);  // Let our custom painting show through
        toggleGroup.setPreferredSize(new Dimension(100, 40));
        
        // Create our two toggle buttons with custom icons
        gridButton = new ViewToggleButton(new GridIcon(), "Grid View");
        listButton = new ViewToggleButton(new ListIcon(), "List View");
        
        // Add click listeners to switch views when buttons are clicked
        gridButton.addActionListener(e -> switchToView("grid"));
        listButton.addActionListener(e -> switchToView("list"));
        
        // Add buttons to the toggle group
        toggleGroup.add(gridButton);
        toggleGroup.add(listButton);
        panel.add(toggleGroup);
        
        // Set grid view as the default active view
        gridButton.setActive(true);
        listButton.setActive(false);
        
        return panel;

    }
    
    
    /**
     * Creates the main content area with both view panels
     * Uses CardLayout to switch between different views
     */
    private void createContentPanels() {
        // CardLayout allows us to stack panels and show only one at a time
        cardLayout = new CardLayout();
        contentPanel = new JPanel(cardLayout);
        contentPanel.setBackground(BACKGROUND_COLOR);
        
        // Create the grid view panel
        createGridView();
        
        // Create the list view panel
        createListView();
        
        // Add both views to the card layout with names we can reference
        contentPanel.add(new JScrollPane(gridViewPanel), "grid");
        contentPanel.add(new JScrollPane(listViewPanel), "list");
        
        // Add the content panel to our main panel
        mainPanel.add(contentPanel, BorderLayout.CENTER);
        
        // Show grid view by default
        cardLayout.show(contentPanel, "grid");
        
    }
    
    /**
     * Creates the grid view panel with sample items arranged in a grid
     */
    private void createGridView() {
        // GridLayout arranges components in a rectangular grid
        gridViewPanel = new JPanel(new GridLayout(3, 4, 10, 10));  // 3 rows, 4 columns, 10px gaps
        gridViewPanel.setBackground(BACKGROUND_COLOR);
        gridViewPanel.setBorder(new EmptyBorder(20, 20, 20, 20));  // Add padding around the grid
        
        // Add sample items to the grid
        for (int i = 1; i <= 12; i++) {
            JPanel itemPanel = createGridItem("Item " + i, "Description for item " + i);
            gridViewPanel.add(itemPanel);
        }
        
    }
    
    
    /**
     * Creates a single item panel for the grid view
     * Each item is a rounded white panel with centered text
     */
    private JPanel createGridItem(String title, String description) {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                // Custom painting to create rounded white background
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                        RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(Color.CYAN);
                g2.fill(new RoundRectangle2D.Double(0, 0, getWidth(), getHeight(), 12, 12));
                g2.dispose();
            }
        };
        
        panel.setLayout(new BorderLayout());
        panel.setOpaque(false);  // Let our custom painting show through
        
        // Create a panel to hold the text elements
        JPanel textPanel = new JPanel();
        textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.Y_AXIS));
        textPanel.setOpaque(false);
        textPanel.setBorder(new EmptyBorder(10, 20, 10, 10));
        
        // Create and style the title label
        JLabel titleLabel = new JLabel(title, SwingConstants.CENTER);
        titleLabel.setFont(new Font("Segoe UI", Font.BOLD, 14));
        titleLabel.setBorder(new EmptyBorder(40, 10, 40, 10));  // Add padding

        // Create and style the description label
        JLabel descLabel = new JLabel(description);
        descLabel.setFont(new Font("Segoe UI", Font.PLAIN, 12));
        descLabel.setForeground(new Color(107, 114, 128));  // Gray text
        descLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        
        // Add labels to text panel with spacing
        textPanel.add(titleLabel);
        textPanel.add(Box.createRigidArea(new Dimension(0, 5)));  // 5px spacing
        textPanel.add(descLabel);
        
        panel.add(textPanel, BorderLayout.CENTER);
        return panel;
        
    }
    
    
    
    /**
     * Creates the list view panel with sample items arranged vertically
     */
    private void createListView() {
        listViewPanel = new JPanel();
        listViewPanel.setLayout(new BoxLayout(listViewPanel, BoxLayout.Y_AXIS));
        listViewPanel.setBackground(BACKGROUND_COLOR);
        listViewPanel.setBorder(new EmptyBorder(20, 20, 20, 20));
        
        // Add sample items to the list
        for (int i = 1; i <= 12; i++) {
            JPanel itemPanel = createListItem("Item " + i, "Description for item " + i);
            listViewPanel.add(itemPanel);
            
            // Add spacing between items (except after the last item)
            if (i < 12) {
                listViewPanel.add(Box.createRigidArea(new Dimension(0, 10)));
            }
        }
        
    }
    
    
    
    /**
     * Creates a single item panel for the list view
     * Each item has a title and description in a horizontal layout
     */
    private JPanel createListItem(String title, String description) {
        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                // Custom painting for rounded white background
                Graphics2D g2 = (Graphics2D) g.create();
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                        RenderingHints.VALUE_ANTIALIAS_ON);
                g2.setColor(Color.YELLOW);
                g2.fill(new RoundRectangle2D.Double(0, 0, getWidth(), getHeight(), 25, 25));
                g2.dispose();
            }
        };
        
        panel.setLayout(new BorderLayout());
        panel.setOpaque(false);
        panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 80));  // Limit height
        
        // Create a panel to hold the text elements
        JPanel textPanel = new JPanel();
        textPanel.setLayout(new BoxLayout(textPanel, BoxLayout.Y_AXIS));
        textPanel.setOpaque(false);
        textPanel.setBorder(new EmptyBorder(10, 20, 10, 10));
        
        // Create and style the title label
        JLabel titleLabel = new JLabel(title);
        titleLabel.setFont(new Font("Segoe UI", Font.BOLD, 14));
        titleLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        
        // Create and style the description label
        JLabel descLabel = new JLabel(description);
        descLabel.setFont(new Font("Segoe UI", Font.PLAIN, 12));
        descLabel.setForeground(new Color(107, 114, 128));  // Gray text
        descLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        
        // Add labels to text panel with spacing
        textPanel.add(titleLabel);
        textPanel.add(Box.createRigidArea(new Dimension(0, 5)));  // 5px spacing
        textPanel.add(descLabel);
        
        panel.add(textPanel, BorderLayout.CENTER);
        return panel;
        
    }
    
    
    /**
     * Switches between grid and list views
     * Also updates the button states to show which view is active
     */
    private void switchToView(String viewName) {
        // Use CardLayout to show the selected view
        cardLayout.show(contentPanel, viewName);
        
        // Update which button appears active
        if (viewName.equals("grid")) {
            gridButton.setActive(true);
            listButton.setActive(false);
        } else {
            gridButton.setActive(false);
            listButton.setActive(true);
        }
        
    }
    
    public static void main(String[] args) {
        
        ViewSwitcher app = new ViewSwitcher();
        app.setVisible(true);
        
    }
    
    
    /**
     * Custom toggle button component
     * This creates a button that can show active/inactive states with hover effects
     */
    class ViewToggleButton extends JButton {
        private boolean isActive = false;    // Whether this button is currently active
        private Icon viewIcon;               // The icon to display
        
        /**
         * Constructor for our custom button
         * @param icon The icon to display on the button
         * @param tooltip Tooltip text shown on hover
         */
        public ViewToggleButton(Icon icon, String tooltip) {
            this.viewIcon = icon;
            
            // Set up button appearance
            setPreferredSize(new Dimension(50, 40));
            setBorderPainted(false);    // Remove default border
            setFocusPainted(false);     // Remove focus indicator
            setContentAreaFilled(false); // Remove default background
            setOpaque(false);           // Make transparent
            setToolTipText(tooltip);    // Set tooltip text
            
            
            // Add mouse hover effects
            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseEntered(MouseEvent e) {
                    // Change color when mouse hovers over button (if not active)
                    if (!isActive) {
                        setForeground(HOVER_COLOR);
                    }
                    repaint();  // Trigger redraw
                }
                
                @Override
                public void mouseExited(MouseEvent e) {
                    // Return to normal color when mouse leaves (if not active)
                    if (!isActive) {
                        setForeground(INACTIVE_COLOR);
                    }
                    repaint();  // Trigger redraw
                }
                
            });
            
            // Set default color
            setForeground(INACTIVE_COLOR);
        }
        
        /**
         * Sets whether this button is in the active state
         * @param active true if button should appear active
         */
        public void setActive(boolean active) {
            isActive = active;
            setForeground(active ? ACCENT_COLOR : INACTIVE_COLOR);
            repaint();  // Trigger redraw
        }
        
        /**
         * Custom painting method to draw the button
         */
        @Override
        protected void paintComponent(Graphics g) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            
            // Draw background highlight if button is active
            if (isActive) {
                g2.setColor( Color.lightGray);
                g2.fill(new RoundRectangle2D.Double(0, 0, getWidth(), getHeight(), 12, 12));
            }
            
            // Draw the icon in the center of the button
            if (viewIcon != null) {
                int iconX = (getWidth() - viewIcon.getIconWidth()) / 2;
                int iconY = (getHeight() - viewIcon.getIconHeight()) / 2;
                viewIcon.paintIcon(this, g2, iconX, iconY);
            }
            
            g2.dispose();
            
        }
        
    }
    
    
    /**
     * Custom icon for Grid View button
     * Draws a simple 2x2 grid of squares
     */
    class GridIcon implements Icon {
        @Override
        public void paintIcon(Component c, Graphics g, int x, int y) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
                    RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(c.getForeground());  // Use the component's foreground color
            g2.setStroke(new BasicStroke(1.5f));  // Set line thickness
            
            // Draw a 2x2 grid of small squares
            int size = 6;     // Size of each square
            int gap = 2;      // Gap between squares
            
            // Top row of squares
            g2.draw(new RoundRectangle2D.Double(x, y, size, size, 1, 1));
            g2.draw(new RoundRectangle2D.Double(x + size + gap, y, size, size, 1, 1));
            
            // Bottom row of squares
            g2.draw(new RoundRectangle2D.Double(x, y + size + gap, size, size, 1, 1));
            g2.draw(new RoundRectangle2D.Double(x + size + gap, y + size + gap, size, size, 1, 1));
            
            g2.dispose();
        
    }
   
        @Override
        public int getIconWidth() { return 14; }
        
        @Override
        public int getIconHeight() { return 14; }
}
   
      
    /**
     * Custom icon for List View button
     * Draws three horizontal lines to represent a list
     */
    class ListIcon implements Icon {
        @Override
        public void paintIcon(Component c, Graphics g, int x, int y) {
            Graphics2D g2 = (Graphics2D) g.create();
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setColor(c.getForeground());  // Use the component's foreground color
            g2.setStroke(new BasicStroke(1.5f));  // Set line thickness
            
            int width = 14;   // Width of each line
            int gap = 4;      // Gap between lines
            
            // Draw three horizontal lines
            g2.draw(new Line2D.Double(x, y, x + width, y));
            g2.draw(new Line2D.Double(x, y + gap, x + width, y + gap));
            g2.draw(new Line2D.Double(x, y + 2 * gap, x + width, y + 2 * gap));
            
            g2.dispose();
        }
        
        @Override
        public int getIconWidth() { return 14; }
        
        @Override
        public int getIconHeight() { return 14; }
        
    }
        
}
  


The Final Result:

Switch Between Grid And List View In Java

Switch Between List And Grid View In Java








Share this

Related Posts

Latest
Previous
Next Post »