在Racket GUI中获取选定的文本字段%

时间:2013-04-27 07:54:08

标签: user-interface scheme racket

我有一个使用The Racket Graphical Interface Toolkit创建GUI的应用程序。 我还有一个包含多个字段的框架,使用以下代码创建:

#lang racket
(require racket/gui)

(define frame (new frame% [label "frame"]))
(define field-1 (new text-field% [label "field-1"] [parent frame])) ;; add field to frame
(define field-2 (new text-field% [label "field-2"] [parent frame]))
(define field-3 (new text-field% [label "field-3"] [parent frame]))

(send frame show #t) ;; show the frame

有没有办法可以动态确定所选字段?因此,将所选字段询问该帧并检索该字段的引用(如果已选中)。

2 个答案:

答案 0 :(得分:3)

text-field%实现了window<%>界面,因此您可以直接使用on-focus

#lang racket
(require racket/gui)

(define my-text-field%
  (class text-field%
    (super-new)
    (define/override (on-focus on?)
      (when on? (printf "~a\n" (send this get-label))))))

(define frame (new frame% [label "Frame"]))
(define field-1 (new my-text-field% [label "field-1"] [parent frame]))
(define field-2 (new my-text-field% [label "field-2"] [parent frame]))
(define field-3 (new my-text-field% [label "field-3"] [parent frame]))

(send frame show #t) ;; show the frame 

答案 1 :(得分:0)

我想我找到了一个解决方案,但它看起来很脏。

我扩展了frame%类,因此我可以捕获on-subwindow-focus个事件。在捕捉这些事件时,我会检查它是否是焦点(而不是非焦点),如果接收器的object-nametext-field%,则可以注册焦点。

实现示例的代码:

#lang racket
(require racket/gui)

(define my-frame%
  (class frame%
    (super-new)
    (define/override (on-subwindow-focus r e)
      (when (and e (eq? 'object:text-field% (object-name r)))
        (printf "selected ~a~n" (send r get-label))))))

(define frame (new my-frame% [label "Frame"]))
(define field-1 (new text-field% [label "field-1"] [parent frame])) ;; add field to frame
(define field-2 (new text-field% [label "field-2"] [parent frame]))
(define field-3 (new text-field% [label "field-3"] [parent frame]))

(send frame show #t) ;; show the frame