Jruby Swing覆盖JFrame关闭事件

时间:2013-09-15 17:26:43

标签: swing jruby

使用Jruby覆盖JFrame中默认关闭操作的正确方法是什么? 我已尝试过以下操作,但只有通过单击窗口装饰关闭按钮关闭窗口才会被禁用。

JFrame初始化方法

def initialize *args
    super("Attendance")
    self.setDefaultCloseOperation(javax.swing.JFrame::DO_NOTHING_ON_CLOSE)
    self.add_window_listener(CloseHelper.new)
    self.minimum_width  = FRAME_WIDTH
    self.minimum_height = FRAME_HEIGHT
    base_font = Font.new("Lucida Grande", 0, 14)
    set_up_components
    self.set_visible true
    self.pack
end

WindowAdapter类

class CloseHelper < WindowAdapter
   def window_closing event
            signouttime=DateTime.now
            cdate=correct_date(signouttime,nil)
      if cdate
        AttendanceModel.fetch("update visitors set signedout=? where datediff(day,signedin,?)=0 and signedout is null",signouttime,signouttime).update
        showerror("Message","Signed out all visitors",nil,nil)
      end
       java.lang.System.exit(0)
      end
end

1 个答案:

答案 0 :(得分:0)

我不确定是否使用正确的方式,但使用JRuby 1.7.4 + JDK 1.7.0_40对我有效:

include Java
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import javax.swing.JFrame
import javax.swing.JPanel
import javax.swing.WindowConstants

def makeUI
  p = JPanel.new
  return p
end
def run
  f = JFrame.new "Attendance"
  f.default_close_operation = WindowConstants::DO_NOTHING_ON_CLOSE
  f.add_window_listener {|e|
    if e.getID == WindowEvent::WINDOW_CLOSING
      puts e
      cdate = false; #correct_date(signouttime,nil)
      if cdate
        #AttendanceModel.fetch("...",signouttime,signouttime).update
        #showerror("Message","Signed out all visitors",nil,nil)
        #XXX continue?
      else
        f.dispose
      end
    end
  }
  f.add makeUI
  f.set_size 320, 240
  f.location_relative_to = nil
  f.visible = true
end
java.awt.EventQueue.invokeLater self