如何给JMenu按钮添加边框

How to add border to JMenu button

我无法为 JMenu 按钮添加边框,setBorder 方法似乎只适用于 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);
    });
}
}

结果如下;我希望 JMenu 和 JMenuItem

周围都有黑框

Picture of created GUI

JMenu 更复杂。您可能需要像这样编辑它:

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

您可以在 https://docs.oracle.com/javase/8/docs/api/javax/swing/UIManager.html

查看 UIManager 的 javadoc

然后您可以检查文件 ${java.home}/lib/swing.properties 以了解类似的属性。

menu.setBorderPainted(true);
UIManager.put("PopupMenu.border",BorderFactory.createLineBorder(Color.RED));