Java how to create drop down button in swing

https://w‮‬ww.theitroad.com

In Java Swing, you can create a drop-down button by combining a JButton and a JPopupMenu. When the button is clicked, the popup menu is displayed below the button, allowing the user to select an option.

Here's an example of how to create a drop-down button:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;

public class DropDownButtonExample {
    public static void main(String[] args) {
        // Create a button with a drop-down arrow
        JButton button = new JButton("Options");
        button.setVerticalTextPosition(JButton.CENTER);
        button.setHorizontalTextPosition(JButton.LEADING);
        
        // Create a popup menu
        JPopupMenu popupMenu = new JPopupMenu();
        JMenuItem menuItem1 = new JMenuItem("Option 1");
        JMenuItem menuItem2 = new JMenuItem("Option 2");
        JMenuItem menuItem3 = new JMenuItem("Option 3");
        popupMenu.add(menuItem1);
        popupMenu.add(menuItem2);
        popupMenu.add(menuItem3);
        
        // Add a listener to the button to display the popup menu
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                popupMenu.show(button, 0, button.getHeight());
            }
        });
        
        // Add the button to a panel and display the panel
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(button, BorderLayout.CENTER);
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

In this example, we create a JButton with the text "Options" and set its vertical and horizontal text positions to display the text to the left of the drop-down arrow.

We also create a JPopupMenu and add three JMenuItem objects to it. When the button is clicked, we display the popup menu using the show() method of the JPopupMenu and pass in the button's coordinates and height to position the menu below the button.

Finally, we add the button to a panel and display it in a frame. When the user clicks the button, the popup menu is displayed, allowing the user to select an option.