1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Swing】Macでメニューバーに任意の名称を表示する方法

Last updated at Posted at 2018-01-28

とっさに出てこなかったのでメモ。

問題

MainWindow.java
public class MainPanel extends JPanel{
	public MainPanel(){
		JButton button1 = new JButton("ボタン");
		add(button1);
	}
	public static void main(String[] args){
		JFrame frame = new JFrame();
		MainPanel mainPanel = new MainPanel();
		frame.getContentPane().add(mainPanel);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	frame.setVisible(true);    
	}
}

解決策

このままでは、メニューバーにMainWindowと出てしまうので、次のようにします。
macOS 10.12.6、JRE 9.0.1で確認済み。

MainWindow.java
public class MainPanel extends JPanel{
	public MainPanel(){
		JButton button1 = new JButton("ボタン");
		add(button1);
	}
}

//別クラスを作る。名前は任意
class Loader{
	public static void main(String[] args){
		//システムのメニューバーを使う
	 	System.setProperty("apple.laf.useScreenMenuBar", "true");
	 	//アプリケーション名の指定
    	System.setProperty("apple.awt.application.name", "test");
		JFrame frame = new JFrame();
		MainPanel mainPanel = new MainPanel();
		frame.getContentPane().add(mainPanel);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	frame.setVisible(true);    
	}
}

補足説明

System.setProperty でJREにプロパティを指定します。この際、 Swingが読み込まれる前に指定する のがポイントです。
JPanelを拡張しているクラスに書くと、Swingが先に読み込まれてしまいます。そのため、Swingと関係しないクラスを別に作り、そこのmainメソッドの先頭に書く必要があります。


追記

Macの画面上部メニューバーにJMenuBarを表示する場合、Java VMの引数として-Dapple.laf.useScreenMenuBar=trueを渡した上で、JFrameを継承したクラスでsetJMenuBar()を呼び出しても同等の効果が得られます。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?