如何为JMenu按钮添加边框

时间:2018-06-01 11:06:44

标签: java swing user-interface jmenu jmenuitem

我无法为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

2 个答案:

答案 0 :(得分:0)

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是否有类似的属性。

答案 1 :(得分:0)

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