2012-12-10 40 views
2

我正在用Java寫一個簡單的繪圖程序,並且我有一個MenuBar(不是JMenuBar)來選擇要繪製的形狀和顏色。我想設置鍵盤快捷鍵在矩形,橢圓和線之間選擇。我知道我可以使用MenuShortcut作爲MenuItems,但這不適用於CheckBoxMenuItems。任何線索我怎麼能做到這一點?如何在Java中的CheckBoxMenuItems上設置加速器快捷鍵?

+0

*使用AWT不會,原因有二 '簡單的' 做它 「Java中的一個簡單的畫圖程序」。 1)AWT的功能比Swing少(你必須更經常地「推出自己的」)2)使用AWT的少數人已經很大程度上忘記了它。 - 你的教授現在要求AWT組件*,*是一個非常壞的跡象。 –

回答

1

也許這需要一個JRadioButtonMenuItem給定用戶將一次繪製一個元素(例如什麼是橢圓線?)。

JRadioButtonMenuItem有一個加速器。例如。

Radio Menu Demo

import javax.swing.*; 

public class RadioMenuDemo { 

    public static void main(String[] args) { 
     Runnable r = new Runnable() { 

      @Override 
      public void run() { 
       JPanel gui = new JPanel(); 

       JMenuBar mb = new JMenuBar(); 
       JMenu shapes = new JMenu("Draw"); 
       mb.add(shapes); 
       ButtonGroup bg = new ButtonGroup(); 
       shapes.setMnemonic('D'); 

       JRadioButtonMenuItem line = new JRadioButtonMenuItem("Line"); 
       line.setAccelerator(KeyStroke.getKeyStroke("L")); 
       shapes.add(line); 
       bg.add(line); 

       JRadioButtonMenuItem oval = new JRadioButtonMenuItem("Oval"); 
       oval.setAccelerator(KeyStroke.getKeyStroke("O")); 
       shapes.add(oval); 
       bg.add(oval); 

       JRadioButtonMenuItem rect = new JRadioButtonMenuItem("Rectangle"); 
       rect.setAccelerator(KeyStroke.getKeyStroke("R")); 
       shapes.add(rect); 
       bg.add(rect); 

       JFrame f = new JFrame("Radio menu items"); 
       f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); 
       f.setJMenuBar(mb); 
       f.pack(); 
       f.setLocationByPlatform(true); 
       f.setVisible(true); 
      } 
     }; 
     SwingUtilities.invokeLater(r); 
    } 
} 
+0

它基本上是一個單選按鈕(使用if語句來禁用其他按鈕),但是我使用的是常規的MenuBar而不是JMenuBar。我正在寫的課程只是我的期末考試的學習方式,而我的教授不讓我們使用JMenuBar –

+0

*「我的教授不讓我們使用JMenuBar」*您的教授需要拖延自己(踢,尖叫)到第三個千年,直到那個時候,他們不應該教別人。 –

+1

是的,我完全同意,並儘快下課時,我通過所有使用的Swing而不是AWT項目的回去,但直到總決賽結束了,我得做他想做的 –