2016-05-16 29 views
0

繼承人一個示例代碼,我嘗試了大部分JButton設置,但無法弄清楚。使用助記符調用JButton按下的動畫

import java.awt.event.*; 

import javax.swing.*; 

public class FailedMnemonic extends JFrame implements Runnable{ 

    /* 
    * 
    * F4 to call button action 
    * ESC to dispose Dialog 
    * 
    * */ 

    public FailedMnemonic() { 
     setSize(200, 100); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     setLocationRelativeTo(null); 
     setLayout(null); 
     Panel p = new Panel(this); 
     p.setBounds(0, 0, 200, 60); 
     add(p); 
    }; 

    public static void main(String args[]){ 
     FailedMnemonic f = new FailedMnemonic(); 
     f.setVisible(true); 
    } 

    @Override 
    public void run() { 

    } 

    public class Panel extends JPanel{ 

     final JFrame f; 
     Action a = new AbstractAction() { 

      @Override 
      public void actionPerformed(ActionEvent arg0) { 
       /*Here should be called the pressed animation from the button, dont know how 
       * maybe i should add the button as parameter on the dialog class so when is dispose the button returns to its original state*/ 
       Dialog d = new Dialog(f, "...", true); 
       d.setSize(500, 200); 
       d.setVisible(true); 
      } 
     }; 

     JButton b = new JButton(); 

     public Panel(JFrame f){ 
      this.f = f; 
      setLayout(null); 
      b.setBounds(0, 0, 150, 50); 
      b.setAction(a); 
      a.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_F4); 
      getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
        KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0), "meh"); 
      getActionMap().put("meh", a); 
      b.setText("CLICK ME"); 
      add(b); 
     } 

     public class Dialog extends JDialog{ 

      public Dialog(JFrame OWNER, String title, boolean modal){ 
       super(OWNER, title, modal); 
       setDefaultCloseOperation(DISPOSE_ON_CLOSE); 
       addEscapeListener(this); 
      } 

      public void addEscapeListener(final JDialog dialog) { 
       ActionListener escListener = new ActionListener() { 
        @Override 
        public void actionPerformed(ActionEvent e) { 
         dialog.setVisible(false); 
        }}; 
       dialog.getRootPane().registerKeyboardAction(escListener, 
         KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), 
         JComponent.WHEN_IN_FOCUSED_WINDOW); 

      } 

     } 

    } 

} 

進口仍然不會成塊碼

+0

'導入沒有進入塊代碼 - 所有的代碼需要縮進4個空格。最簡單的方法是選擇代碼,然後單擊「{}」按鈕。 – camickr

回答

2

不要叫你的類「框架」和「對話」。有這個名字的AWT組件,所以它變得混亂。使用更多的描述名稱(即使它是快速演示代碼)。

呼叫JButton的使用記憶

在Windows上我得到的動畫可以使用Alt + F4,這是記憶的時候按下動畫。當我使用鍵綁定的F4時,我沒有看到動畫。

這很有意義,因爲使用Key Bindings您只需將KeyStroke映射到Action即可。它不知道該操作屬於一個按鈕。

如果你想看到的按鈕動畫,那麼我建議你需要:

  1. 添加正常ActionListener添加到按鈕,顯示對話框
  2. 創建的鍵綁定的Action。這個行動然後會調用button.doClick()

請注意,您可能還想查看Escape Key and Dialog以獲取更完整的操作。此操作將支持使用退出鍵關閉組合框下拉菜單。

+0

我試過了你的建議。它實際上工作,動畫觸發器,現在問題發生在對話框再次處理動作觸發並且對話框再次出現時。 –

+0

'當對話被處置時,動作再次觸發,對話框再次出現。「 - 這就是爲什麼我說你需要單獨的ActionLIstener和Action。您沒有正確實施建議,也沒有重新發布您的代碼,所以我無法進一步幫助。 – camickr