javaswinguser-interfacejmenujmenuitem

How to add border to JMenu button


I can't add border to JMenu button, looks like setBorder methods works only with JMenuItem.

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

public class Test extends JFrame {
public Test() {
   initUI();
}

private void initUI() {


    // creating menuBar
    JMenuBar menuBar = new JMenuBar();

    // creating menu and adding border
    JMenu menu = new JMenu("Some menu");
    menu.setBorder(BorderFactory.createLineBorder(Color.black, 3));

    // creating item and adding border (the same way)
    JMenuItem item1 = new JMenuItem("Some item");
    item1.setBorder(BorderFactory.createLineBorder(Color.black, 3));

    // adding all together
    menu.add(item1);
    menuBar.add(menu);
    setJMenuBar(menuBar);

    // basic settings for the window
    setTitle("Testing JMenu");
    setSize(360, 250);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public static void main(String[] args) {
    EventQueue.invokeLater(() -> {
        Test test =new Test();
        test.setVisible(true);
    });
}
}

The result is as follows; I expected black frames around both JMenu and JMenuItem

Picture of created GUI


Solution

  • JMenu is more complex. You might have to edit it like this:

    UIManager.put("PopupMenu.border", new LineBorder(Color.RED));
    

    You can check the javadocs for UIManager at https://docs.oracle.com/javase/8/docs/api/javax/swing/UIManager.html

    You can then check the file ${java.home}/lib/swing.properties for similar properties.