2017-03-16 59 views
0

我正嘗試使用「Calculator like」鍵功能在Groovy應用程序中編寫代碼。所以,我想調用揮杆動作,當我:使用Groovy Swing Builder的Java密鑰綁定

  • 按JButton的
  • 按相應的鍵盤按鍵,沒有matther是否有重點的JButton與否。

也許是最好的解決方案是使用Java的按鍵綁定,如下所述: https://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html

繼Groovy和Java的組合似乎運作良好:

package packageSwingTest4 
import groovy.swing.SwingBuilder 
import javax.swing.* 
import java.awt.* 
import javax.swing.WindowConstants as WC 
class SwingTest4 { 
    def static b 
    static void main(args) { 
     def swing = new SwingBuilder()  
     def f2Action = swing.action(name:"F2", shortDescription:"F2 button", accelerator:"F2") { 
     println "F2 pressed" 
     } 

     swing.edt { 
     def f=frame(title: 'Keborad Binding test', size:[400,300],defaultCloseOperation: JFrame.EXIT_ON_CLOSE, show: true) { 
       panel { 
       b = button(text: 'F2', actionPerformed:{println "FFFF2222 pressed"}) 
       b.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F2"),"F2 pressed") 
       b.getActionMap().put("F2 pressed",f2Action) 
      } 
     } 
    } 
} 

}

但我不喜歡用這種方式來結合Groovy/Java,就像我會這樣: - 與Groovy結構相關的鬆散的良好結構GUI - 我必須分別定義Actions並且不像Groovy swing builder那樣「很好」

您是否使用純粹的Groovy/SwingBuilder瞭解我的問題的「更清潔」解決方案?我寧願不使用按鍵偵聽器,按鍵綁定,..

感謝您的幫助和建議

回答

1

不是100%肯定,但你的意思是這樣的:

import groovy.swing.* 
import javax.swing.* 

def swing = new SwingBuilder()  

def f2Action = swing.action(name:"F2 text", shortDescription:"F2 button", keyStroke:"F2") { 
    println "F2 pressed" 
} 

swing.edt { 
    frame(title: 'Keborad Binding test', size:[400,300],defaultCloseOperation: JFrame.HIDE_ON_CLOSE, show: true) { 
     panel { 
      button(text: 'F2', 
        actionPerformed:{ println "FFFF2222 pressed" }) { 
       action(f2Action) 
      } 
     } 
    } 
} 
+0

是,這是我正在尋找的解決方案。感謝您的快速響應。我簡化的最終代碼如下: – jirka

0
 def swing = new SwingBuilder() 

     def f2Action = swing.action(name:"F2 text", shortDescription:"F2 button", focus: JComponent.WHEN_IN_FOCUSED_WINDOW, keyStroke:"F2") { 
     println "F2 pressed" 
    } 
     def f3Action = swing.action(name:"F3 text", shortDescription:"F2 button", keyStroke:"F3") { 
     println "F3 pressed" 
    } 

     swing.edt { 
     frame(title: 'Keborad Binding test', size:[400,300],defaultCloseOperation: JFrame.HIDE_ON_CLOSE, show: true) { 
       panel { 
         button('F2') {action(f2Action)} 
         button('F3') {action(f3Action)} 
      } 
      } 
     }