简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM