2013-06-04 40 views
0

我想在彈出菜單中包含一些靜態文本。我希望它看起來就像其他菜單項一樣,只是不可選擇。我已經嘗試的方法:將靜態文本添加到Java Swing菜單的最佳方式是什麼?

  • 將禁用的JMenuItem添加到菜單中。雖然這會導致正確的字體和對齊方式,但會導致文本呈淺灰色並且幾乎無法讀取。

  • 將JLabel添加到菜單中。這看起來很醜陋;該標籤使用與常規菜單項不同的字體,並且不對齊(菜單項爲左側的圖標留出空間,標籤不會這樣做)。

    JPopupMenu popupMenu = new JPopupMenu(); 
    JLabel label = new Label("Static text); 
    popupMenu.add(label); 
    JMenuItem menuItem = new JMenuItem("Disabled menu item); 
    menuItem.setEnabled(false); 
    popupMenu.add(menuItem); 
    menuItem = new JMenuItem("Regular item); 
    popupMenu.add(menuItem); 
    

我失去了一些其他的方式來添加靜態文本到使用相同的字體和對齊方式爲常規菜單項,但不可選擇一個菜單,不接受鍵盤焦點,而不是突出當鼠標懸停在它上面?

+0

從用戶的角度來看,如果文字看起來同其他可單擊選項,這將是令人困惑/煩人。如果你只是想分類菜單選項,也許子菜單會是一個更好的方法? – DannyMo

+0

嗯注意JLabel錯誤,我看到幾次,看起來不錯,把JSeparator放在JLabel下,然後放到JPopupMenu的底部,使用JLabel.setFont(myJMenuItem.getFont或從UIManager獲取這個值給JMenuItem) – mKorbel

+0

some LookAndFeels已經爲JPopuMenu,JMenu和JMenuItems實現了垂直標籤 – mKorbel

回答

0

以下工作適合我。只需添加一個JLabel到JPanel並添加的JPanel您JPopupMenu的

JPanel panelLabel = new JPanel();  
JLabel lblSomeText = new JLabel("Some text"); 
lblSomeText.setFont(menuItem.getFont()); 
lblSomeText.setForeground(menuItem.getForeground()); 
panelLabel.add(lblSomeText); 
popupMenu.add(panelLabel); 
+1

問題是標籤不對齊相同。標籤顯示爲與菜單左側齊平,而菜單項左側留有一點空間。也許這取決於外觀和感覺;我正在開發Linux並使用默認系統外觀(即GTK)。 –

相關問題