簡體   English   中英

將靜態文本添加到Java Swing菜單的最佳方法是什么?

[英]What's the best way to add static text to a Java Swing menu?

我想在彈出菜單中包含一些靜態文本。 我希望它看起來像其他任何菜單項一樣,只是無法選擇。 我嘗試的方式:

  • 將禁用的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); 

我是否缺少其他方法可以向菜單添加靜態文本,該菜單使用與常規菜單項相同的字體和對齊方式,但是它是不可選擇的,不接受鍵盤焦點,並且當鼠標懸停在菜單上時也不會突出顯示嗎?

以下對我來說很好用。 只需將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);

對於OP來說已經太晚了,但是在無需費心L&F猜測的情況下實現同一件事的一種簡單方法是,刪除當鼠標經過按鈕時突出顯示按鈕的事件偵聽器。

JMenuItem menuItem = ......
if (menuItem.getModel() instanceof DefaultButtonModel) {
    DefaultButtonModel model = (DefaultButtonModel)menuItem.getModel();
    model.setArmed(false);
    for (ChangeListener cl : model.getChangeListeners()) {
        //System.err.format("yep, removing %s%n", cl);
        model.removeChangeListener(cl);
    }
}
menuItem.setFocusable(false);
menuItem.setForeground ....
menuItem.setBackground ....
menuItem.setFont ....
menuItem.setHorizontalAlignment ....

請注意,這有點極端,因為如果在“現在是標簽的按鈕”上注冊了任何其他事件偵聽器,它們也會受到干擾,並且沒有有意義的方式將它們區分開。

您也可以執行JLabel ,但是當然,您需要做很多JMenuItem / AbstractButton代碼和L&F為您完成的定位和繪制工作。

(並且不要被Swing中的“翻轉”功能所迷惑;它通常正是用於這種事情,但是在菜單和菜單項中不使用。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM