How can I modify the window menu of a JFrame in Java ? That's the one (in Windows) at the top left, behind the application icon, that has items such as 'Restore', 'Move', 'Minimize', 'Resize'...
A menu bar handles keyboard shortcuts for menu items, passing them along to its child menus. (Keyboard shortcuts, which are optional, provide the user with an alternative to the mouse for invoking a menu item and the action that is associated with it.) Each menu item can maintain an instance of MenuShortcut .
Use MenuItem. setTitle(). If this isn't what you needed, you have to be more specific.
The object of MenuItem class adds a simple labeled menu item on menu. The items used in a menu must belong to the MenuItem or any of its subclass. The object of Menu class is a pull down menu component which is displayed on the menu bar. It inherits the MenuItem class.
Unfortunately I've only found a way to do this with the "metal decoration" (with that I mean doing JFrame.setDefaultLookAndFeelDecorated(true);
). I will of course update the answer if I find one with the system LaF, but I think this is still worth an answer.
Output:
Code:
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.io.BufferedReader;
import java.io.UnsupportedEncodingException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
public class Example {
public Example() {
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame();
JMenu systemMenu = getSystemMenu(frame);
systemMenu.add(new JMenuItem("New JMenuItem"), 0);
for (Component component : systemMenu.getPopupMenu().getComponents()) {
if (component.toString().contains("JMenu")) {
((JMenuItem) component).setForeground(Color.RED);
}
}
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JMenu getSystemMenu(JFrame frame) {
for (Component c1 : frame.getLayeredPane().getComponents()) {
if (c1.toString().contains("MetalTitlePane")) {
for (Component c2 : ((Container) c1).getComponents()) {
if (c2.toString().contains("SystemMenuBar")) {
return (JMenu) ((Container) c2).getComponent(0);
}
}
}
}
return null;
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new Example();
}
});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With