是否可以創建包含按鈕的自定義JMenuItem
?例如,纔有可能創建具有類似這樣的項目的:Java中的自定義JMenuItems
+----------------------------------------+
| JMenuItem [ Button | Button | Button ] |
+----------------------------------------+
是否可以創建包含按鈕的自定義JMenuItem
?例如,纔有可能創建具有類似這樣的項目的:Java中的自定義JMenuItems
+----------------------------------------+
| JMenuItem [ Button | Button | Button ] |
+----------------------------------------+
我懷疑是否有一種簡單的方法可以做到這一點。你可以這樣做:
JMenuItem item = new JMenuItem("Edit ");
item.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 0));
JButton copy = new JButton("Copy");
copy.setMargin(new Insets(0, 2, 0, 2));
item.add(copy);
menu.add(item);
但有幾個問題:
一)當你點擊該按鈕菜單不會關閉。因此,代碼需要添加到您的ActionListener中。b)菜單項不響應像左/右箭頭這樣的按鍵事件,因此無法使用鍵盤將焦點放在按鈕上。這將涉及UI更改菜單項,我不知道從哪裏開始。
我只是使用標準的UI設計創建子菜單。
+1標準:-) – kleopatra 2011-05-12 10:25:37
我敢肯定有,像我個人會使用單獨的菜單項,只是把它們並排併爲每個單獨的按鈕設置動作監聽器。棘手的部分將把它們放在像JPanel這樣的容器中,並將它們放入流佈局或網格佈局
老問題,但你可以用JToolBar中做到這一點很容易...
//Make a popup menu with one menu item
final JPopupMenu popupMenu = new JPopupMenu();
JMenuItem menuItem = new JMenuItem();
//The panel contains the custom buttons
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.LINE_AXIS));
panel.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(Box.createHorizontalGlue());
JToolBar toolBar = new JToolBar();
JButton toolBarButton = new JButton();
toolBarButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
popupMenu.setVisible(false); //hide the popup menu
//other actions
}
});
toolBar.setFloatable(false);
toolBar.add(toolBarButton);
panel.add(toolBar);
//Put it all together
menuItem.add(panel);
menuItem.setPreferredSize(new Dimension(menuItem.getPreferredSize().width, panel.getPreferredSize().height)); //do this if your buttons are tall
popupMenu.add(menuItem);
鏈接到圖像打開一個空白頁 – kleopatra 2011-05-12 10:24:56