Racket GUI 类的 Racket 代码示例

3

我来自Java和Python,对于Racket中的面向对象代码理解有些困难。

  1. Given

    (define food%
     (class object%
        (super-new)
        (init-field name)
        (field (edible? #t))
        (init-field healthy?)
        (init-field tasty?) ) )
    

    define a superclass fruit% of food% which always has the healthy? value of #t, and which doesn't require one to set the healthy? field when defining a new fruit.

  2. In racket/gui, define a super-class of button% called text-input-button% which has two new fields, output (ideally of type text-field%) and text (ideally a string), and whose callback field has as its value a function which appends the value of the text field to the current contents of the value of the output field. Practically, the buttons would input characters into the text-field specified.

我认为如果我能看到这两个例子,我的困惑会得到很大的解决。也就是说,我正在寻找“适当”或教科书上的方法来做到这一点,而不是使用set!这样一些兜圈子的技巧,除非这是所有适当方法的实质。

1个回答

4

(1) 你真的是想让fruit%成为food%的超类吗?在我看来,你应该希望fruit%是一个子类。这里假设它是一个子类:

(define fruit%
  (class food%
    (super-new [healthy? #t])))

(2)为此,我认为最好基于一个panel%创建一个新的小部件来存储这两个子小部件:

(define text-input-button%
  (class horizontal-panel%
    (super-new)
    (init-field text)
    ;; callback for the button
    (define (callback button event)
      (define new-value (string-append (send output get-value) text))
      (send output set-value new-value))
    (define button (new button% [label "Click me"]
                                [parent this]
                                [callback callback]))
    (define output (new text-field% [label "Output"]
                                    [parent this]))))

;; testing it out
(define f (new frame% [label "Test"]))
(define tib (new text-input-button% [text "foo"] [parent f]))
(send f show #t)

如果你真的想将它作为 button% 子类,可以这样做,但我认为这种方法更简洁。


你对问题(1)的回答已经足够帮我搞清楚了。但是对于(2),我认为子类实际上更加简洁:
(define text-input-button% (class button% (init-field output-text-field) (init-field text-value) (super-new [label text-value] [callback (λ(b e)(send (send output-text-field get-editor) insert text-value))]) )) 你也理解了我的意图:我是指子类。你的回答非常有帮助:非常感谢!
- Monad

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接