示例#1
0
def initial():
    global f  ##文件
    global txt
    global number_of_occurrence
    reload(sys)
    sys.setdefaultencoding('utf-8')
    ctr.init()
    ctr.set_value('flag', 0)
    ctr.set_value('reload_check', 0)
    ctr.set_value('world_boss_check', 0)
    ctr.set_value('raid_check', 0)
    #ctr.set_value('raid_check',None)
    number_of_occurrence = 0
    ctr.set_value('max_level_check', None)
    ctr.set_value('return_check', 0)
    ticks = time.time()
    date = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime(ticks)) + '_日誌'
    f = open(date + '.txt', 'w', 0)

    frame = JFrame("Log")
    txt = JTextArea(19, 55)
    scrollPane = JScrollPane(txt)
    ##frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.setLocation(2000, 100)
    frame.setSize(480, 450)
    frame.setLayout(FlowLayout())
    ##label = JLabel('記錄:')
    scrollPane.setHorizontalScrollBarPolicy(
        JScrollPane.HORIZONTAL_SCROLLBAR_NEVER)
    ##frame.add(label)
    frame.add(scrollPane)
    frame.setVisible(True)
示例#2
0
    def initResultados(self):
        diag = JFrame()
        self.lineas = list()
        self.areaResultados = JTextArea()
        numLineas = self.readResultados()

        panelResultados = JPanel()
        #panelResultados.setAutoscrolls(True)
        panelResultados.setBorder(BorderFactory.createEtchedBorder())
        panelResultados.setLayout(GridLayout(0, 1))

        pane = JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                           JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
        pane.viewport.view = self.areaResultados

        #pane.getViewport().add(panelResultados)

        diag.setTitle("RESULTADOS OBTENIDOS")

        diag.setSize(1000, 450)
        diag.setLayout(BorderLayout())
        diag.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        diag.setLocationRelativeTo(None)
        diag.setVisible(True)

        panelResultados.add(pane)
        diag.add(panelResultados, BorderLayout.CENTER)
示例#3
0
class UI(object):
    def __init__(self, game):

        self.frame = JFrame("Tic Tac Toe",
                             defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE)

        self.panel = JPanel(GridLayout(3,3))
        self.buttons = []
        self.game = game
        for row in range(3):
            for col in range(3):
                self.buttons.append(TicTacButton(row,col,'',actionPerformed=self.clicked_button))

        self.panel.add
        self.frame.add(self.panel)
        for b in self.buttons:
            self.panel.add(b)

        self.frame.pack()
        self.show()


    def show(self):
        self.frame.size = 600,600
        self.frame.visible = True


    def clicked_button(self, event):
        button = event.getSource()
        print 'current_player', self.game.current_player
        if self.game.current_player.level == 'human' and self.game.state=='next':
            button.text = self.game.current_player.xo
            self.game.update(button)
        else:
            pass
示例#4
0
 def run(self):
     frame = JFrame('Spinner4',
                    layout=FlowLayout(),
                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
     frame.add(JSpinner(SpinnerDateModel()))
     frame.pack()
     frame.setVisible(1)
示例#5
0
    def run(self):
        frame = JFrame('FlowLayout',
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        cp = frame.getContentPane()
        #-----------------------------------------------------------------------
        # The alignment can be one of the following values:
        #-----------------------------------------------------------------------
        #       cp.setLayout( FlowLayout( FlowLayout.LEFT ) )
        #       cp.setLayout( FlowLayout( FlowLayout.RIGHT ) )
        cp.setLayout(FlowLayout())  # FlowLayout.CENTER  is the default value
        #       cp.setLayout( FlowLayout( FlowLayout.LEADING ) )
        #       cp.setLayout( FlowLayout( FlowLayout.TRAILING ) )

        for name in '1,two,Now is the time...'.split(','):
            frame.add(JButton(name))

        #-----------------------------------------------------------------------
        # The ComponentOrientation can be one of the following values
        # Note: The default value is related to the system locale
        #-----------------------------------------------------------------------
#       cp.setComponentOrientation( ComponentOrientation.LEFT_TO_RIGHT )
#       cp.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT )

        frame.setSize(350, 100)
        frame.setVisible(1)
示例#6
0
文件: main.py 项目: jooneyp/PhoyStick
 def handle(self):
     print 'connection from', self.client_address
     conn = self.request
     while 1:
         msg = conn.recv(20)
         if msg == "keymap":
             print "keymapping!"
             keymapFrame = JFrame(
                 'Key Mapping Configuration',
                 defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
                 size=(300, 500))
             keyButton = JButton('Press any key in iPhone')
             keymapFrame.add(keyButton)
             keymapFrame.visible = True
             while 1:
                 recvKey = conn.recv(20)
                 keyButton.setLabel("%s?" % recvKey)
                 keyInput = raw_input()
                 keynum[recvKey] = keyInput
                 keyButton.setText('Press any key in iPhone')
                 if recvKey == "keymap":
                     keymapFrame.visible = False
                     break
         if msg == "quit()":
             conn.close()
             print self.client_address, 'disconnected'
             break
         print self.client_address, msg
示例#7
0
    def run( self ) :
        frame = JFrame(
            'Box1',
            locationRelativeTo = None,
            defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        )
        name = 'A'
        size = Dimension( 46, 26 )
        vBox = Box.createVerticalBox()
        for row in range( 5 ) :
            hBox = Box.createHorizontalBox()
            for col in range( 5 ) :
                button = JButton( name )
#               button = JButton(
#                   name,
#                   size = size,
#                   minimumSize = size,
#                   maximumSize = size,
#                   preferredSize = size
#               )
                hBox.add( button )
                self.showSizes( name, button )
                name = chr( ord( name ) + 1 )
            vBox.add( hBox )
        frame.add( vBox )
        frame.pack()
        frame.setVisible( 1 )
示例#8
0
    def bg(self, panel2, e):
        bground = JFrame()
        bground.setTitle("Change Background")
        bground.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
        bground.setSize(350, 100)
        bground.setLocationRelativeTo(None)
        bground.setVisible(True)
        bground.setResizable(False)

        panel = JPanel()
        #panel.setBackground(Color(46, 64, 96))
        bground.getContentPane().add(panel)

        path = JLabel("File:")
        panel.add(path)

        path2 = JTextField()
        path2.setPreferredSize(Dimension(180, 20))
        panel.add(path2)

        browse = JButton("Browse file",
                         actionPerformed=lambda e: self.browse(path2, e))
        panel.add(browse)

        change = JButton(
            "Change",
            actionPerformed=lambda e: self.change(path2.getText(), panel2, e))
        panel.add(change)

        bground.add(panel)
示例#9
0
    def run(self):
        frame = JFrame('horizontalBox',
                       locationRelativeTo=None,
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        vert = Box.createVerticalBox()
        vert.add(Box.createGlue())
        vert.add(JButton('<>'))
        vert.add(Box.createVerticalStrut(5))
        vert.add(JButton('<>'))
        vert.add(Box.createVerticalStrut(5))
        vert.add(JButton('<>'))
        vert.add(Box.createGlue())

        hor = Box.createHorizontalBox()
        hor.add(Box.createGlue())
        hor.add(JButton('<>'))
        hor.add(Box.createHorizontalStrut(5))

        hor.add(vert)

        hor.add(Box.createHorizontalStrut(5))
        hor.add(JButton('<>'))
        hor.add(Box.createGlue())

        frame.add(hor)
        frame.pack()
        frame.setVisible(1)
示例#10
0
 def run(self):
     frame = JFrame('List1',
                    size=(250, 200),
                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
     data = 'Now is the time for all good spam'.split(' ')
     frame.add(JList(data))
     frame.setVisible(1)
示例#11
0
    def onInfo(self, e):
        info = JFrame()
        info.setTitle("Info")
        info.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
        info.setSize(410, 400)
        info.setLocationRelativeTo(None)
        info.setResizable(False)
        info.setVisible(True)

        panel = JPanel()
        #panel.setBackground(Color(46, 64, 96))
        #panel.setLayout(GridLayout(0, 2))

        logo = JLabel(ImageIcon("/icons/logo.jpg"))
        panel.add(logo)

        f = Font("", Font.ITALIC, 40)
        title = JLabel("Stylus OS 1.0 beta")
        title.setFont(f)
        panel.add(title)

        f = Font("", Font.ITALIC, 14)
        copyright = JLabel(
            "Copyright (c) 2016 Niccolo' Ciavarella. All rights reserved.")
        copyright.setFont(f)
        panel.add(copyright)

        info.getContentPane().add(panel)
        info.add(panel)
    def run( self ) :
        frame = JFrame(
            'SecConfigReport_02',
            size = ( 300, 300 ),
            locationRelativeTo = None,
            defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        )

        data = []
        text = AdminTask.generateSecConfigReport()
        for line in text.splitlines()[ 2: ] :
            data.append(
                [
                    info.strip() for info in
                    line[ :-2 ].split( ';' )
                ]
            )

        frame.add(
            JScrollPane(
                JTable( data, ';;;'.split( ';' ) )
            )
        )

        frame.pack()
        frame.setVisible( 1 )
示例#13
0
    def run(self):
        frame = JFrame('SecConfigReport_09',
                       size=(500, 300),
                       locationRelativeTo=None,
                       componentResized=self.frameResized,
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        data = []
        text = AdminTask.generateSecConfigReport()
        #-----------------------------------------------------------------------
        # The RegExp was added to replace multiple blanks with a single one
        #-----------------------------------------------------------------------
        for line in text.splitlines()[2:]:
            data.append([
                re.sub('  +', ' ', info.strip())
                for info in line[:-2].split(';')
            ])

        self.table = table = JTable(
            reportTableModel(
                data,
                ';;;'.split(';'),
            ),
            selectionMode=ListSelectionModel.SINGLE_SELECTION)
        table.setDefaultRenderer(String, reportRenderer())
        self.setColumnWidths(table)
        scroller = JScrollPane(table)
        scroller.getViewport().addChangeListener(rowFinder(table))
        frame.add(scroller)

        frame.pack()
        frame.setVisible(1)
        frame.setMinimumSize(frame.getSize())
示例#14
0
    def run( self ) :
        frame = JFrame(
           'BorderLayout',
            layout = BorderLayout(),
            defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        )

        data = [
                   [ 'PAGE_START', BorderLayout.PAGE_START ],
                   [ 'PAGE_END'  , BorderLayout.PAGE_END   ],
                   [ 'LINE_START', BorderLayout.LINE_START ],
                   [ 'LINE_END'  , BorderLayout.LINE_END   ],
               ]

        for name, pos in data :
            frame.add( JButton( name ), pos )

        big = JButton(
                       'CENTER',
                        preferredSize = Dimension( 256, 128 )
                     )
        frame.add( big, BorderLayout.CENTER )

        frame.pack()
        frame.setVisible( 1 )
示例#15
0
def show():
    """ adapted from here: http://wiki.gephi.org/index.php/Toolkit_-_Reuse_the_Preview_Applet"""
    from javax.swing import JFrame
    from java.awt import BorderLayout

    pc = PreviewController
    pc.refreshPreview()

    # New Processing target, get the PApplet
    target = pc.getRenderTarget("processing")
    applet = target.getApplet()
    applet.init()

    # Refresh the preview and reset the zoom
    try:
        pc.render(target)
    except Exception:
        # throws sun.dc.pr.PRError: sun.dc.pr.PRError: setPenT4: invalid pen transformation (singular)
        pass
    target.refresh()
    target.resetZoom()

    # Add the applet to a JFrame and display
    frame = JFrame("Preview")
    frame.setLayout(BorderLayout())

    # frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.add(applet, BorderLayout.CENTER)

    frame.pack()
    frame.setVisible(True)
示例#16
0
    def run(self):
        frame = JFrame('Available Fonts',
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        #-----------------------------------------------------------------------
        # First, we a local graphics environment (LGE) instance.  Then, we call
        # its getAvailableFontFamilyNames() method to obtain the list of all
        # available font names.
        #-----------------------------------------------------------------------
        lge = GraphicsEnvironment.getLocalGraphicsEnvironment()
        fontNames = lge.getAvailableFontFamilyNames()

        #-----------------------------------------------------------------------
        # The JTextArea will be used to hold the names of the available fonts.
        # Unfortunately, we don't know, for certain, how many font names are
        # present.  So, we need to have the JTextArea be within a JScrollPane,
        # "just in case" too many names exist for us to display at one time. ;-)
        #-----------------------------------------------------------------------
        frame.add(
            JScrollPane(
                JTextArea('\n'.join(fontNames), editable=0, rows=8,
                          columns=32)))

        frame.pack()
        frame.setVisible(1)
示例#17
0
    def run( self ) :
        frame = JFrame(
            'WSAShelp_01',
            locationRelativeTo = None,
            defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        )
#       text = Help.help()
#       tabs = text.count( '\t' )
#       text = Help.help().expandtabs()
#       rows = text.count( '\n' ) + 1
#       cols = max( [ len( x ) for x in text.splitlines() ] )
#       cols = max( [ len( x.expandtabs() ) for x in text.splitlines() ] )
#       print '\nrows: %d  cols: %d  tabs: %d' % ( rows, cols, tabs )
        frame.add(
            JScrollPane(
                JTextArea(
#                   text,
                    Help.help().expandtabs(),
                    20,
                    80,
                    font = Font( 'Courier' , Font.PLAIN, 12 )
                )
            )
        )
        frame.pack()
        size = frame.getSize()
#       print 'frame.getSize():', size
        loc = frame.getLocation()
#       print 'frame.getLocation():', loc
        loc.x -= ( size.width  >> 1 )
        loc.y -= ( size.height >> 1 )
        frame.setLocation( loc )
        frame.setVisible( 1 )
示例#18
0
    def run(self):
        frame = JFrame('Table11',
                       size=(300, 170),
                       locationRelativeTo=None,
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        menuBar = JMenuBar()
        resize = JMenu('AUTO_RESIZE')

        bGroup = ButtonGroup()
        for name, value in self.info:
            rb = JRadioButtonMenuItem(name,
                                      actionPerformed=self.handler,
                                      selected=(name == 'Rest'))
            bGroup.add(rb)
            resize.add(rb)
        menuBar.add(resize)
        frame.setJMenuBar(menuBar)

        headings = 'T/F,Date,Integer,Float,Double'.split(',')
        model = myTM(self.data, headings)
        self.table = table = JTable(
            model, selectionMode=ListSelectionModel.SINGLE_SELECTION)
        table.getColumnModel().getColumn(model.getColumnCount() -
                                         1  # i.e., last column
                                         ).setCellRenderer(myRenderer())
        setColumnWidths(table)

        frame.add(JScrollPane(table))
        frame.setVisible(1)
示例#19
0
    def run(self):
        frame = JFrame('flexible Box',
                       locationRelativeTo=None,
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        print '\nscreenSize:', Toolkit.getDefaultToolkit().getScreenSize()

        box = Box.createHorizontalBox()
        box.add(Box.createGlue())
        box.add(Box.createRigidArea(Dimension(5, 5)))
        box.add(JLabel('Name:'))
        box.add(Box.createRigidArea(Dimension(5, 5)))
        self.tf = box.add(
            JTextField(
                10  # ,
                #               maximumSize = Dimension(   2000, 20 )
                #               maximumSize = Dimension(  20000, 20 )
                #               maximumSize = Dimension( 200000, 20 )
            ))
        box.add(Box.createRigidArea(Dimension(5, 5)))
        box.add(JButton('Submit', actionPerformed=self.buttonPress))
        box.add(Box.createRigidArea(Dimension(5, 5)))
        box.add(Box.createGlue())

        frame.add(box)
        frame.pack()
        frame.setVisible(1)
示例#20
0
def createMainWindow():
    # Create window
    frame = JFrame('Epiphany Core Visualisation',
                   defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
                   size=(660, 675))

    # Main layout
    mainLayout = JPanel()
    frame.add(mainLayout)

    # Title
    #title = JLabel('hello', JLabel.CENTER)
    #mainLayout.add(title)

    # Cores
    corepanel = JPanel(GridLayout(8, 8))
    global cores
    cores = []
    for i in range(0, 64):
        core = JPanel(GridLayout(2, 1))
        core.setPreferredSize(Dimension(80, 80))
        corename = '(' + str(i % 8) + ',' + str(i / 8) + ')'
        namelabel = JLabel(corename, JLabel.CENTER)
        namelabel.setFont(Font("Dialog", Font.PLAIN, 18))
        portname = str(i + MINPORT)
        portlabel = JLabel(portname, JLabel.CENTER)
        portlabel.setFont(Font("Dialog", Font.PLAIN, 16))
        core.add(namelabel)
        core.add(portlabel)
        core.setBackground(Color.BLACK)
        corepanel.add(core)
        cores.append(core)
    mainLayout.add(corepanel)

    frame.visible = True
示例#21
0
class positionDialog(JFrame):
    def __init__(self):
        self.frame = JFrame("CellCropper: Experiment details", size=(400,200))
        self.frame.setLocation(20,120)
        self.Panel = JPanel(GridLayout(4,2))
        self.frame.add(self.Panel)
        self.Panel.add(JLabel("Date:"))
        self.dateField = JTextField( str(date.today()), 8 )
        self.Panel.add(self.dateField)
        self.strainField = JTextField( "2926",4 )
        self.Panel.add(self.strainField)
        self.tempField = JTextField( "34",2 )
        self.Panel.add(self.tempField)
        self.ODField = JTextField( "0.5",3 )
        self.Panel.add(self.ODField)
        self.condField = JTextField( "0.5",3 )
        self.Panel.add(self.condField)

        self.OKButton = JButton("OK",actionPerformed=closeAndMakePos)
        self.Panel.add(self.OKButton)
        self.frame.pack()
        WindowManager.addWindow(self.frame)
        self.show()

    def show(self):
        self.frame.visible = True
    
    def close(self):
        return self.dateField.text, self.strainField.text, self.tempField.text, self.ODField.text, self.condField.text
        WindowManager.removeWindow(self.frame)
        self.frame.dispose()
示例#22
0
    def run(self):
        frame = JFrame('FrameMethods',
                       size=(1000, 500),
                       locationRelativeTo=None,
                       layout=GridLayout(0, 2),
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        self.one = self.parse(self.textFile('JFrame Methods.txt'))
        self.left = JTextArea(self.one,
                              20,
                              40,
                              editable=0,
                              font=Font('Courier', Font.PLAIN, 12))

        frame.add(JScrollPane(self.left))

        self.two = self.parse(self.textFile('JInternalFrame Methods.txt'))
        self.right = JTextArea(self.two,
                               20,
                               40,
                               editable=0,
                               font=Font('Courier', Font.PLAIN, 12))
        frame.add(JScrollPane(self.right))

        frame.setJMenuBar(self.makeMenu())

        frame.setVisible(1)
示例#23
0
    def run(self):
        frame = JFrame('Table7',
                       size=(300, 150),
                       locationRelativeTo=None,
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        headings = 'T/F,Date,Integer,Float,Double'.split(',')
        model = myTM(self.data, headings)
        table = JTable(model,
                       selectionMode=ListSelectionModel.SINGLE_SELECTION)
        table.getColumnModel().getColumn(model.getColumnCount() -
                                         1  # i.e., last column
                                         ).setCellRenderer(myRenderer())

        #----------------------------------------------------------
        # Adjust the width of the columns using only header text
        #----------------------------------------------------------
        hRenderer = table.getTableHeader().getDefaultRenderer()
        for col in range(model.getColumnCount()):
            column = table.getColumnModel().getColumn(col)
            comp = hRenderer.getTableCellRendererComponent(
                None,  # Table
                column.getHeaderValue(),  # value
                0,  # isSelected = false 
                0,  # hasFocus = false
                -1,  # row #
                col  # col #
            )
            width = comp.getPreferredSize().width
            #           print 'col: %d  previous: %d  current: %d' % ( col, column.getPreferredWidth(), width )
            column.setPreferredWidth(width)

        frame.add(JScrollPane(table))
        frame.setVisible(1)
def show():
    """ adapted from here: http://wiki.gephi.org/index.php/Toolkit_-_Reuse_the_Preview_Applet"""
    from javax.swing import JFrame
    from java.awt import BorderLayout

    pc = PreviewController
    pc.refreshPreview();
     
    # New Processing target, get the PApplet
    target = pc.getRenderTarget("processing")
    applet = target.getApplet()
    applet.init()
     
    # Refresh the preview and reset the zoom
    try:
        pc.render(target) 
    except Exception:
        # throws sun.dc.pr.PRError: sun.dc.pr.PRError: setPenT4: invalid pen transformation (singular)
        pass
    target.refresh()
    target.resetZoom()
     
    # Add the applet to a JFrame and display
    frame = JFrame("Preview")
    frame.setLayout(BorderLayout())
     
    # frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.add(applet, BorderLayout.CENTER)
     
    frame.pack()
    frame.setVisible(True)
示例#25
0
def test_swing():
    frame = JFrame("Hello Jython")
    button = JButton("Pulsar", actionPerformed = hello)
    frame.add(button)
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.setSize(200, 100)
    frame.show()
示例#26
0
 def handle(self):
     print 'connection from', self.client_address
     conn = self.request
     while 1:
         msg = conn.recv(20)
         if msg == "keymap":
             print "keymapping!"
             keymapFrame = JFrame('Key Mapping Configuration',
                            defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
                            size = (300, 500)
                            )
             keyButton = JButton('Press any key in iPhone')
             keymapFrame.add(keyButton)
             keymapFrame.visible = True
             while 1:
                 recvKey = conn.recv(20)
                 keyButton.setLabel("%s?" % recvKey)
                 keyInput = raw_input()
                 keynum[recvKey] = keyInput
                 keyButton.setText('Press any key in iPhone')
                 if recvKey == "keymap":
                     keymapFrame.visible = False
                     break
         if msg == "quit()":
             conn.close()
             print self.client_address, 'disconnected'
             break
         print self.client_address, msg
示例#27
0
    def run(self):
        frame = JFrame('MethodTable2',
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        #-----------------------------------------------------------------------
        # Get the text to be processed
        #-----------------------------------------------------------------------
        helpText = Help.help().expandtabs()

        #-----------------------------------------------------------------------
        # Verify our help text parsing routine
        #-----------------------------------------------------------------------
        headings = ['Method', 'Description / Abstract']

        #-----------------------------------------------------------------------
        # Let's try to highlight every instance of "help" in the table
        #-----------------------------------------------------------------------
        data = self.parseMethodHelp(helpText)
        for r in range(len(data)):
            for c in range(len(data[r])):
                data[r][c] = self.hiliteText(data[r][c], 'help')

        #-----------------------------------------------------------------------
        # Create the JTable using the massaged data and column headings
        #-----------------------------------------------------------------------
        table = JTable(data, headings, font=Font('Courier', Font.PLAIN, 12))
        frame.add(JScrollPane(table), 'Center')

        frame.pack()
        self.center(frame)
        frame.setVisible(1)
示例#28
0
    def run(self):
        frame = JFrame('List6',
                       size=(200, 220),
                       layout=GridLayout(1, 2),
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        panel = JPanel(layout=GridLayout(0, 1))
        self.buttons = {}
        for name in 'First,Last,Before,After,Remove'.split(','):
            self.buttons[name] = panel.add(self.button(name))

        self.text = panel.add(JTextField(10))
        self.addInputMethodListener(self)
        #       self.addTextListener( self )
        frame.add(panel)

        data = ('Now is the time for all good spam ' +
                'to come to the aid of their eggs').split(' ')
        model = DefaultListModel()
        for word in data:
            model.addElement(word)
        self.info = JList(model,
                          valueChanged=self.selection,
                          selectionMode=ListSelectionModel.SINGLE_SELECTION)
        frame.add(JScrollPane(self.info, preferredSize=(200, 100)))
        frame.setVisible(1)
def changePasswordForm(check):
    global frame
    global tfOldPassword
    global tfNewPassword
    global tfConfirmPassword
    global value

    value = check

    frame = JFrame("Change Password")
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    frame.setSize(500, 350)
    frame.setLocation(200, 200)
    frame.setLayout(None)
    frame.setVisible(True)

    panel = JPanel()
    panel.setSize(500, 350)
    panel.setLocation(0, 0)
    panel.setLayout(None)
    panel.setVisible(True)
    panel.setBackground(Color.LIGHT_GRAY)

    heading = JLabel("Change Password")
    heading.setBounds(200, 30, 150, 40)

    lbOldPassword = JLabel("Old Password")
    lbNewPassword = JLabel("New Password")
    lbConfirmPassword = JLabel("Confirm Password")

    tfOldPassword = JTextField()
    tfNewPassword = JTextField()
    tfConfirmPassword = JTextField()

    lbOldPassword.setBounds(50, 100, 150, 30)
    lbNewPassword.setBounds(50, 150, 150, 30)
    lbConfirmPassword.setBounds(50, 200, 150, 30)

    tfOldPassword.setBounds(220, 100, 150, 30)
    tfNewPassword.setBounds(220, 150, 150, 30)
    tfConfirmPassword.setBounds(220, 200, 150, 30)

    btnSave = JButton("Save", actionPerformed=clickSave)
    btnCancel = JButton("Cancel", actionPerformed=clickCancel)

    btnSave.setBounds(350, 280, 100, 30)
    btnCancel.setBounds(50, 280, 100, 30)

    panel.add(heading)
    panel.add(lbOldPassword)
    panel.add(lbNewPassword)
    panel.add(lbConfirmPassword)
    panel.add(tfOldPassword)
    panel.add(tfNewPassword)
    panel.add(tfConfirmPassword)
    panel.add(btnSave)
    panel.add(btnCancel)

    frame.add(panel)
示例#30
0
 def run( self ) :
     frame = JFrame(
         'List1a',
         size = ( 250, 200 ),
         defaultCloseOperation = JFrame.EXIT_ON_CLOSE
     )
     frame.add( JList( self.data() ) )
     frame.setVisible( 1 )
示例#31
0
 def run(self):
     frame = JFrame('Global Security')
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
     security = AdminConfig.list('Security')
     status = AdminConfig.showAttribute(security, 'enabled')
     frame.add(JLabel('Security enabled: ' + status))
     frame.pack()
     frame.setVisible(1)
示例#32
0
 def run(self):
     frame = JFrame('NumbEdit',
                    size=(500, 100),
                    locationRelativeTo=None,
                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
     table = JTable(tm())
     frame.add(JScrollPane(table))
     frame.setVisible(1)
示例#33
0
 def run_fn(event):
     log_window = JFrame('Galahad Log')
     log_text_area = JTextArea()
     log_text_area.editable = False
     log_window.setSize(400, 500)
     log_window.add(log_text_area)
     log_window.show()
     log_text_area.append('sdfsdfsdfsdfsd %d' % 3)
示例#34
0
 def run(self):
     frame = JFrame('Spinner1',
                    layout=FlowLayout(),
                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
     daysOfWeek = [dow for dow in DFS().getWeekdays() if dow]
     frame.add(JSpinner(SpinnerListModel(daysOfWeek)))
     frame.pack()
     frame.setVisible(1)
示例#35
0
 def run_fn(event):
     log_window = JFrame('Galahad Log')
     log_text_area = JTextArea()
     log_text_area.editable = False
     log_window.setSize(400, 500)
     log_window.add(log_text_area)
     log_window.show()
     log_text_area.append('sdfsdfsdfsdfsd %d' % 3)
示例#36
0
def run(sketch):
    from javax.swing import JFrame
    from processing.core import PApplet

    class Main(PApplet):

        def __init__(self, sketch):
            self.sketch = sketch
            P5_set_instance(self)

        def setup(self):
            self.sketch['setup']()

        def draw(self):
            self.sketch['draw']()

        def mousePressed(self, evt):
            P5_register_mouse_event(evt)
            self.sketch['mousePressed']()

        def mouseReleased(self, evt):
            P5_register_mouse_event(evt)

        def mouseClicked(self, evt):
            P5_register_mouse_event(evt)
            self.sketch['mouseClicked']()

        def mouseEntered(self, evt):
            P5_register_mouse_event(evt)

        def mouseExited(self, evt):
            P5_register_mouse_event(evt)

        def mouseDragged(self, evt):
            P5_register_mouse_event(evt)
            self.sketch['mouseDragged'](evt)

        def mouseMoved(self, evt):
            P5_register_mouse_event(evt)
            self.sketch['mouseMoved'](evt)

        def getField(self, name):
            # rqd due to PApplet's using frameRate and frameRate(n) etc.
            return self.class.superclass.getDeclaredField(name).get(self)

    if __name__ == '__main__' or True:
        frame = JFrame(title="Processing",
            resizable=0,
            defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        panel = Main(sketch)
        frame.add(panel)
        panel.init()
        while panel.defaultSize and not panel.finished:
            pass
        frame.pack()
        frame.visible = 1
示例#37
0
class View(JComponent):
    def __init__(self, obj, location, size=(800, 600), keys=None):
        JComponent.__init__(self)
        self.location = list(location)
        self.buffer = FrameBuffer(
            size[0], size[1], FrameBuffer.SAMPLINGMODE_NORMAL)
        self.obj = obj
        self.frame = JFrame(keyPressed=self.keyPressed,
                            keyReleased=self.keyReleased)
        self.frame.add(self)
        self.size = size
        self.frame.pack()
        self.frame.size = size
        self.frame.visible = True
        self.clearColor = Color(0x666666)
        self.keys = keys

    def paint(self, g):
        x, y, z = self.location
        self.obj.world.camera.setPosition(x, -y, z)
        self.obj.world.camera.lookAt(SimpleVector(0, 0, 0))

        self.buffer.clear(self.clearColor)
        self.obj.world.renderScene(self.buffer)
        self.obj.world.draw(self.buffer)
        self.buffer.update()
        self.buffer.display(g)
        self.repaint()

    def keyReleased(self, event):
        if self.keys is not None and hasattr(self.keys, 'key_released'):
            self.keys.key_released(KeyEvent.getKeyText(event.keyCode))

    def keyPressed(self, event):
        if self.keys is not None and hasattr(self.keys, 'key_pressed'):
            self.keys.key_pressed(KeyEvent.getKeyText(event.keyCode))
        if event.keyCode == KeyEvent.VK_ESCAPE:
            self.frame.dispose()
        elif event.keyCode == KeyEvent.VK_PAGE_UP:
            self.obj.sch.rate *= 1.1
            self.frame.title = 'rate: %1.3f' % self.obj.sch.rate
        elif event.keyCode == KeyEvent.VK_PAGE_DOWN:
            self.obj.sch.rate /= 1.1
            self.frame.title = 'rate: %1.3f' % self.obj.sch.rate
        elif event.keyCode == KeyEvent.VK_Z:
            self.location[2] += 1
        elif event.keyCode == KeyEvent.VK_X:
            self.location[2] -= 1
        elif event.keyCode == KeyEvent.VK_W:
            self.location[1] += 1
        elif event.keyCode == KeyEvent.VK_S:
            self.location[1] -= 1
        elif event.keyCode == KeyEvent.VK_A:
            self.location[0] += 1
        elif event.keyCode == KeyEvent.VK_D:
            self.location[0] -= 1
示例#38
0
 def __init__(self):
     w = JFrame("Settler-o-matic", size = (120,680))
     w.setAlwaysOnTop(True)
     
     pause = JButton("Pause", actionPerformed = self.pause)
     w.add(pause, SOUTH)
     
     w.visible = True
     self.window = w
     self.pause = pause
示例#39
0
    def run(self, query, print_urls = True, pr_weight =0.4, verbose = False):
        """this function basically runs a query""" 
        self.query = parse_query(query, self.reader)
        start_time = time.clock()
        
        self.n_show = 10
        
        if self.ah_flag is True:
            doc_ids, score, auth_ids, auth_score, hub_ids, hub_score = self.retrieve(verbose = verbose)
        elif self.pr_flag is True:
            doc_ids, score, pr_ids, pr = self.retrieve(pr_weight = pr_weight, verbose = verbose)
        else:
            doc_ids, score = self.retrieve(verbose = verbose)		

        end_time = time.clock()
        frame = JFrame('Ragav\'s Search Engine',
                        defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
                        size = (100, 200)
                        )  
        panel = JPanel(GridLayout(0,1))
        frame.add(panel)                           

        print "in total  " + str(end_time - start_time) + " seconds for retrieval"
        
        if print_urls is True:
            # panel.add ( JLabel("vector space retreival" ) )
            for i in xrange(self.n_show):
                d = self.reader.document(doc_ids[i])			
                panel.add ( JLabel (d.getFieldable("path").stringValue().replace("%%", "/") ) )
                print "doc: [" + str(doc_ids[i]) + "], score: [" + str(score[doc_ids[i]]) +  "], url: " + d.getFieldable("path").stringValue().replace("%%", "/")

            if self.ah_flag is True:
                # panel.add ( Jlabel("authorities based retreival" ) )
                for i in xrange(self.n_show):
                    d = self.reader.document(auth_ids[i])			
                    panel.add (  JLabel (d.getFieldable("path").stringValue().replace("%%", "/") ) )

                # panel.add ( JLabel("hubs based retreival" ) )
                for i in xrange(self.n_show):
                    d = self.reader.document(hub_ids[i])			
                    panel.add (  JLabel  ( d.getFieldable("path").stringValue().replace("%%", "/") ) )


            elif self.pr_flag is True:
                # panel.add ( JLabel("page rank based retreival" ) )
                for i in xrange(self.n_Show):
                    d = self.reader.document(pr_ids[i])			
                    panel.add ( JLabel ( d.getFieldable("path").stringValue().replace("%%", "/") ) )


        print  "retrieval complete. "
        print  "..........................................................................."
        frame.pack() 
        frame.visible = True            
        return d 
示例#40
0
class MainWindow(object):
    def __init__(self):
        self.frame = JFrame('Hello, Jython!',
                            defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
                            size=(400, 600))
        bag_layout = GridBagLayout()
        self.frame.layout = bag_layout
        grid_constraints = GridBagConstraints()

        format_1_string_label = JLabel("Format 1 string:")
        grid_constraints.weightx = 0.1
        grid_constraints.weighty = 0.1
        grid_constraints.gridy = 0
        grid_constraints.fill = GridBagConstraints.NONE
        self._add_component(format_1_string_label, bag_layout, grid_constraints)

        self.input_textbox = JTextArea()
        grid_constraints.weightx = 1
        grid_constraints.weighty = 1
        grid_constraints.gridy = 1
        grid_constraints.fill = GridBagConstraints.BOTH
        input_scroll_pane = JScrollPane(self.input_textbox)
        input_scroll_pane.verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS
        self._add_component(input_scroll_pane, bag_layout, grid_constraints)

        output_string_label = JLabel("Output:")
        grid_constraints.weightx = 0.1
        grid_constraints.weighty = 0.1
        grid_constraints.gridy = 2
        grid_constraints.fill = GridBagConstraints.NONE
        self._add_component(output_string_label, bag_layout, grid_constraints)

        self.output_textbox = JTextArea()
        grid_constraints.weightx = 1
        grid_constraints.weighty = 1
        grid_constraints.gridy = 3
        grid_constraints.fill = GridBagConstraints.BOTH
        self.output_textbox.editable = False
        output_scroll_pane = JScrollPane(self.output_textbox)
        output_scroll_pane.verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS
        self._add_component(output_scroll_pane, bag_layout, grid_constraints)

    def _add_component(self, component, layout, constraint):
        layout.setConstraints(component, constraint)
        self.frame.add(component)

    def show(self):
        self.frame.visible = True
        listener = InputTextDocumentListener(self.input_textbox, self.output_textbox)
        self.input_textbox.document.addDocumentListener(listener)
示例#41
0
class View:
    def __init__(self):
        self.stats=None
        self.frame=JFrame('Statistics',visible=True,layout=BorderLayout())

        self.graph=GraphPanel(self,componentResized=lambda event: self.graph.update())
        self.frame.add(self.graph)

        self.options=OptionsPanel(self)
        self.frame.add(self.options,BorderLayout.WEST)


        self.model_selection=ModelSelectionPanel(self)
        self.frame.add(self.model_selection,BorderLayout.NORTH)

        self.frame.add(RunPanel(self),BorderLayout.SOUTH)

        self.frame.size=(800,600)
    def selected_params(self):
        return self.options.parameters.get_selected()

    def file_changed(self,event):
        if event.stateChange==ItemEvent.SELECTED:
            self.select_model(event.item)



    def select_model(self,name):
        self.model_selection.files.selectedItem=name
        self.stats=stats.Stats(name)
        self.options.update()
        self.graph.update()
示例#42
0
def install(helper):
  	print('install called'); 
	
	frame = JFrame("Please Input Values")
	frame.setLocation(100,100)
	frame.setSize(500,400)
	frame.setLayout(None)

	lbl1 = JLabel("Input1: ")
	lbl1.setBounds(60,20,60,20)
	txt1 = JTextField(100)
	txt1.setBounds(130,20,200,20)
	lbl2 = JLabel("Input2: ")
	lbl2.setBounds(60,50,100,20)
	txt2 = JTextField(100)
	txt2.setBounds(130,50,200,20)
	lbl3 = JLabel("Input3: ")
	lbl3.setBounds(60,80,140,20)
	txt3 = JTextField(100)
	txt3.setBounds(130,80,200,20)
	lbl4 = JLabel("Input4: ")
	lbl4.setBounds(60,110,180,20)
	txt4 = JTextField(100)
	txt4.setBounds(130,110,200,20)
	
	def getValues(event):
		print "clicked"
		ScriptVars.setGlobalVar("Input1",str(txt1.getText()))
		print(ScriptVars.getGlobalVar("Input1"))
		ScriptVars.setGlobalVar("Input2",str(txt2.getText()))
		print(ScriptVars.getGlobalVar("Input2"))
		ScriptVars.setGlobalVar("Input3",str(txt3.getText()))
		print(ScriptVars.getGlobalVar("Input3"))
		ScriptVars.setGlobalVar("Input4",str(txt4.getText()))
		print(ScriptVars.getGlobalVar("Input4"))		
		
	btn = JButton("Submit", actionPerformed = getValues)
	btn.setBounds(160,150,100,20)
		
	frame.add(lbl1)
	frame.add(txt1)
	frame.add(lbl2)
	frame.add(txt2)
	frame.add(btn)
	frame.add(lbl3)
	frame.add(txt3)
	frame.add(lbl4)
	frame.add(txt4)
	frame.setVisible(True)
def main():
	
	activeLayers=getActiveLayers()

	if len(activeLayers)==0:
		JOptionPane.showMessageDialog(None, 
			"Add and activate at least one vector layer in the view. Retry!",
			"Batch Transparency", JOptionPane.WARNING_MESSAGE)
		return
	else:
		numFLyrVect=0
		for i in range(len(activeLayers)):
			if activeLayers[i].getClass().getCanonicalName()=="com.iver.cit.gvsig.fmap.layers.FLyrVect":
				numFLyrVect=numFLyrVect+1
		if numFLyrVect==0:
			JOptionPane.showMessageDialog(None, 
				"You have to add and activate at least one vector layer in the view. Retry!", 
				"Batch Transparency", JOptionPane.WARNING_MESSAGE)
			return
		else:
			global frame, outCheckbox, fillCheckbox, slider
			frame = JFrame("Batch Transparency", defaultCloseOperation=JFrame.DISPOSE_ON_CLOSE, 
				bounds=(100, 100, 450, 80), layout=FlowLayout(), resizable=0)

			outCheckbox = JCheckBox("outline", 1)
			fillCheckbox = JCheckBox("fill", 1)

			# Create a horizontal slider with min=0, max=100, value=50
			slider = JSlider()
			slider.setPreferredSize(Dimension(200, 50))
			slider.setValue(100)
			slider.setMajorTickSpacing(25)
			slider.setMinorTickSpacing(5)
			slider.setPaintTicks(1)
			slider.setPaintLabels(1)

			applyButton = JButton("Apply", actionPerformed=action)
			acceptButton = JButton("Accept", actionPerformed=accept)
			
			frame.add(outCheckbox)
			frame.add(fillCheckbox)
			frame.add(slider)
			frame.add(applyButton)
			frame.add(acceptButton)
			
			frame.show()
	return
示例#44
0
class CodeView(ca.nengo.util.VisiblyMutable.Listener):
    def __init__(self,network):
        self.network=network
        self.frame=JFrame(network.name)
        self.frame.visible=True
        self.frame.layout=BorderLayout()
        self.frame.size=(800,600)


        self.code=JTextArea(generate(self.network),editable=False)
        scroll=JScrollPane(self.code)
        scroll.viewport.scrollMode=JViewport.SIMPLE_SCROLL_MODE   # not sure why this is needed -- if not done, text is corrupted when scrolling
        self.frame.add(scroll)

        self.network.addChangeListener(self)

    def changed(self,event):
        self.code.text=generate(self.network)
示例#45
0
def _open():
    frame = JFrame('Galahad',
                   defaultCloseOperation=WindowConstants.EXIT_ON_CLOSE)
    panel = JPanel(GridLayout(5, 2))
    frame.add(panel)

    chosen_values = {}
    def create_file_choice_button(name, label_text):
        button = JButton('Click to select')
        label = JLabel(label_text)
        file_chooser = JFileChooser()
        
        def choose_file(event):
            user_did_choose_file = (file_chooser.showOpenDialog(frame) ==
                                   JFileChooser.APPROVE_OPTION)
            if user_did_choose_file:
                file_ = file_chooser.getSelectedFile();
                button.text = chosen_values[name] = str(file_)
        button.actionPerformed = choose_file

        panel.add(label)
        panel.add(button)

    create_file_choice_button('binary',     'Binary archive:')
    create_file_choice_button('source',     'Source archive:')
    create_file_choice_button('output_dir', 'Output directory:')

    panel.add(JLabel(''))
    panel.add(JLabel(''))

    def run_fn(event):
        log_window = JFrame('Galahad Log')
        log_text_area = JTextArea()
        log_text_area.editable = False
        log_window.setSize(400, 500)
        log_window.add(log_text_area)
        log_window.show()
        log_text_area.append('sdfsdfsdfsdfsd %d' % 3)
        
    panel.add(JButton('Run analysis', actionPerformed=run_fn))
    panel.add(JButton('Quit', actionPerformed=lambda e: sys.exit(0)))

    frame.setSize(300, 160)
    frame.visible = True
示例#46
0
 def startGui(self):
     frame = JFrame("Life", defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
     (R, C) = (self.numRows, self.numCols)
     gridPanel = JPanel(GridLayout(R, C))
     self.checkBoxes = [[JCheckBox() for c in range(C)] for r in range(R)]
     self.grid = [[False for c in range(C)] for r in range(R)]
     for r in range(R):
         for c in range(C):
             gridPanel.add(self.checkBoxes[r][c])
     frame.add(gridPanel)
     buttonPanel = JPanel(FlowLayout())
     stepButton = JButton("Step", actionPerformed=self._step)
     runButton = JToggleButton("Run", actionPerformed=self._run)
     buttonPanel.add(stepButton)
     buttonPanel.add(runButton)
     frame.add(buttonPanel, SOUTH)
     frame.pack()
     frame.locationRelativeTo = None
     frame.visible = True
示例#47
0
def createAndShowGUI():
    # Create the GUI and show it. As with all GUI code, this must run
    # on the event-dispatching thread.
    frame = JFrame("GUI Development ")
    frame.setSize(500, 600)
    frame.setLayout(BorderLayout())
    splitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT)
    
    #Create and set up the content pane.
    psimures= ResourcePanel()
    psimures.setOpaque(True)
    pconfig = ConfigurationPanel()
    pconfig.setOpaque(True)      #content panes must be opaque

    # show the GUI
    splitPane.add(psimures)
    splitPane.add(pconfig)
    frame.add(splitPane)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
    frame.setVisible(True)
示例#48
0
def createAndShowGUI():
    # Create the GUI and show it. As with all GUI code, this must run
    # on the event-dispatching thread.
    frame = JFrame("MAE ")
    frame.setSize(1024, 768)
    panel= JPanel()
    panel.setLayout(GridBagLayout())
    
    #Create and set up the content pane.
    psimures= SimoutPanel()
    psimures.setOpaque(True)
    c = GridBagConstraints()
    c.fill = GridBagConstraints.HORIZONTAL
    c.weightx = 1
    c.gridx = 0
    c.gridy = 0
    panel.add(psimures, c);
    pmeasure= MeasPanel()
    pmeasure.setOpaque(True)
    c = GridBagConstraints()
    c.fill = GridBagConstraints.HORIZONTAL
    c.weightx = 1
    c.gridx = 0
    c.gridy = 1
    panel.add(pmeasure, c);
    preport = ReportPanel()
    preport.setOpaque(True)
    c = GridBagConstraints()
    c.fill = GridBagConstraints.VERTICAL
    c.weighty = 1
    c.gridx = 1
    c.gridy = 0
    c.gridheight= 2
    panel.add(preport,c)
    # show the GUI
    
    frame.add(panel)
#     frame.add(pmeasure)
#     frame.add(preport)
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
    frame.setVisible(True)
示例#49
0
def createMainWindow():
	# Create window
	frame = JFrame('Epiphany Core Visualisation',
		defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
		size = (660,675)
	)

	# Main layout
	mainLayout = JPanel()
	frame.add(mainLayout)

	# Title
	#title = JLabel('hello', JLabel.CENTER)
	#mainLayout.add(title)

	# Cores
	corepanel = JPanel(GridLayout(8,8))
	global cores
	cores = []
	for i in range(0,64):
		core = JPanel(GridLayout(2,1))
		core.setPreferredSize(Dimension(80,80))
		corename = '(' + str(i%8) + ',' + str(i/8) + ')'
                namelabel = JLabel(corename, JLabel.CENTER)
		namelabel.setFont(Font("Dialog", Font.PLAIN, 18))
		portname = str(i+MINPORT)
		portlabel = JLabel(portname, JLabel.CENTER)
	        portlabel.setFont(Font("Dialog", Font.PLAIN, 16))
		core.add(namelabel)
		core.add(portlabel)
		core.setBackground(Color.BLACK)
		corepanel.add(core)
		cores.append(core)
	mainLayout.add(corepanel)

	frame.visible = True
示例#50
0
    def menuItemClicked(self, caption, messageInfo):
        response = messageInfo[0].getResponse()
        strResponse = ''.join([chr(c%256) for c in response])
        frame = JFrame('DOM XSS',size = (300,300))
        parentPanel = JPanel()


        #printedCode = JTextPane(text = strResponse)
        #'''
        #colored code
        printedCode = JTextPane()
        styledDoc = printedCode.getStyledDocument()
        style = printedCode.addStyle('ColoredCode',None)
        self.filter2(strResponse,styledDoc,style)
        #'''
        #Scroll Bar
        scrollPanel = JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
        scrollPanel.preferredSize = 1500,800
        scrollPanel.viewport.view = printedCode

        #Final Inclusion of Panels
        parentPanel.add(scrollPanel)
        frame.add(parentPanel)
        frame.visible = True
示例#51
0
  def __init__(self):
    frame = JFrame("Jython JTable Example")
    frame.setSize(500, 250)
    frame.setLayout(BorderLayout())

    self.tableData = [
      ['Mouse 1', eventNames[0], eventScriptType[0]],
      ['Mouse 2', eventNames[1] , eventScriptType[1]],
      ['Mouse 3', eventNames[2], eventScriptType[2]],
      ['Mouse 1 Shift', eventNames[3], eventScriptType[3]],
      ['Mouse 2 Shift',eventNames[4], eventScriptType[4]],
      ['Mouse 3 Shift',eventNames[5], eventScriptType[5]],
      ['Mouse 1 Control',eventNames[6], eventScriptType[6]],
      ['Mouse 2 Control',eventNames[7], eventScriptType[7]],
      ['Mouse 3 Control',eventNames[8], eventScriptType[8]],
       ]
    colNames = ('Script/Event','Name','Type')
    dataModel = DefaultTableModel(self.tableData, colNames)
    self.table = JTable(dataModel)

    scrollPane = JScrollPane()
    scrollPane.setPreferredSize(Dimension(400,200))
    scrollPane.getViewport().setView((self.table))

    panel = JPanel()
    panel.add(scrollPane)

    frame.add(panel, BorderLayout.CENTER)

    self.label = JLabel('Hello from Jython')
    frame.add(self.label, BorderLayout.NORTH)
    button = JButton('Save Settings',actionPerformed=self.setText)
    frame.add(button, BorderLayout.SOUTH)
    exitButton = JButton('Exit',actionPerformed=self.myExit)
    frame.add(exitButton, BorderLayout.EAST)

    frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
    frame.setVisible(True)
示例#52
0
class StopWatch(Runnable):
    def __init__(self):
        self.frame = JFrame("StopWatch", defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        self.start = JButton("Start", actionPerformed=self.start)
        self.frame.add(self.start, BorderLayout.WEST)
        self.stop = JButton("Stop", actionPerformed=self.stop)
        self.frame.add(self.stop, BorderLayout.EAST)
        self.label = JLabel(" " * 45)
        self.frame.add(self.label, BorderLayout.SOUTH)
        self.frame.pack()

    def start(self, event):
        self.started = Calendar.getInstance().getTimeInMillis()
        self.label.setText("Running")

    def stop(self, event):
        elapsed = Calendar.getInstance().getTimeInMillis() - self.started
        self.label.setText("Elapsed: %.2f seconds" % (float(elapsed) / 1000.0))

    def run(self):
        self.frame.setVisible(1)
def getGUI(sym_dict):
	global frame, outCheckbox, fillCheckbox, slider, colorTF, widthTF
	frame = JFrame("Border Symbology", defaultCloseOperation=JFrame.DISPOSE_ON_CLOSE, 
		       bounds=(100, 100, 450, 200), layout=FlowLayout(), resizable=0)

	colorL = JLabel('Color: ')
	colorTF = JTextField(20)
	color = sym_dict["color"]
	color = Color(color.getRed(), color.getGreen(), color.getBlue(), sym_dict["alpha"])
	colorTF.setBackground(color)
	colorTF.setText(color.toString())

	colorB = JButton('...', actionPerformed=colorChooser)
	frame.add(colorL)
	frame.add(colorTF)
	frame.add(colorB)

	widthL = JLabel('Width: ')
	widthTF = JTextField(3)
	widthTF.setText(str(sym_dict["width"]))
	frame.add(widthL)
	frame.add(widthTF)

	alphaL = JLabel('Transparency: ')
	frame.add(alphaL)

	# Create a horizontal slider with min=0, max=100, value=50
	slider = JSlider()
	slider.setPreferredSize(Dimension(200, 50))
	slider.setValue(sym_dict["alpha"]*100/255)
	slider.setMajorTickSpacing(25)
	slider.setMinorTickSpacing(5)
	slider.setPaintTicks(1)
	slider.setPaintLabels(1)

	applyButton = JButton("Apply", actionPerformed=action)
	acceptButton = JButton("Accept", actionPerformed=accept)

	frame.add(slider)
	frame.add(applyButton)
	frame.add(acceptButton)

	frame.show()
示例#54
0
class PythonWindow(KeyListener):
    def __init__(self):
        self.frame = JFrame("Python Window")
        self.historyList = JList(DefaultListModel())
        self.historyList.cellRenderer = MyListCellRenderer()
        #self.historyPanel.layout = BoxLayout(
        #    self.historyPanel,
        #    BoxLayout.Y_AXIS
        #)
        scrollpane = JScrollPane()
        #    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
        #    JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
        #)
        # scrollpane.preferredSize = 400, 800
        inputPanel = JPanel()
        inputPanel.layout = GridLayout(1, 1)
        self.input = JTextArea("")
        self.input.border = BorderFactory.createEmptyBorder(5, 5, 5, 5)
        self.input.tabSize = 4
        self.input.font = Font("Monospaced", Font.PLAIN, 12)
        #self.input.preferredSize = 500, 200 
        self.input.addKeyListener(self)
        #self.button = JButton('Run', actionPerformed=self.run)
        inputPanel.add(self.input)
        #inputPanel.add(self.button)
        scrollpane.viewport.view = self.historyList
        self.frame.add(scrollpane, BorderLayout.CENTER)
        self.frame.add(inputPanel, BorderLayout.PAGE_END)
        self.frame.size = 500, 600
        self.frame.visible = False
    def toggle_visibility(self):
        self.frame.visible = not self.frame.visible
    def add(self, text, type="input"):
        self.historyList.model.addElement({"text": text, "type": type})
        self.historyList.validate()
        self.frame.validate()
        last = self.historyList.model.getSize() - 1
        self.historyList.ensureIndexIsVisible(last)
    def write(self, text):
        self.add(text, "output")
    def run(self, evt):
        source = self.input.text
        if not source.strip():
            self.input.text = ""
            return
        processed_source = source.replace("$", "geo.")
        code = interface.compileinteractive(processed_source)
        if code in ("continue", "error"):
            code = interface.compilemodule(processed_source)
            if code == "error":
                return
        self.add(source.strip())
        result = interface.run(code)
        if result == "OK":
            self.input.text = ""
    def keyPressed(self, evt):
        pass
    def keyReleased(self, evt):
        pass
    def keyTyped(self, evt):
        if evt.keyChar == '\n':
            # Only try to run compound statements when they end with
            # two \n
            source = self.input.text
            lines = source.split("\n")
            if lines[0].rstrip().endswith(":") and not source.endswith("\n\n"):
                for i, c in enumerate(lines[-2]):
                    if c not in ' \t': break
                else:
                    self.run(evt)
                    return
                prefix = lines[-2][:i]
                if lines[-2].endswith(":"):
                    prefix += '\t'
                self.input.text = source + prefix
            else:
                self.run(evt)
示例#55
0
class MandersPlugin(ImageListener, WindowAdapter):

	def __init__(self):
		self.imp = None
		self.preview = None
		self.createMainWindow()
		self.cells = None
		self.files = []
		self.results = ResultsTable()
		ImagePlus.addImageListener(self)
		self.selectInputDir()
		self.selectOutputDir()
		self.pairs = []
		self.methods = []
		self.processNextFile()

	def selectInputDir(self):
		inputDialog = DirectoryChooser("Please select a directory contaning your images")
		inputDir = inputDialog.getDirectory()
		for imageFile in os.listdir(inputDir):
			self.files.append(inputDir + imageFile)

	def selectOutputDir(self):
		outputDialog = DirectoryChooser("Please select a directory to save your results")
		self.outputDir = outputDialog.getDirectory()
		
	def closeImage(self):
		if self.imp is not None:
			self.imp.close()
			self.imp = None
		if self.preview is not None:
			self.preview.close()
			self.preview = None

	def openImage(self, imageFile):
		try:
			images = BF.openImagePlus(imageFile)
			self.imp = images[0]
		except UnknownFormatException:
			return None
		if self.imp.getNChannels() < 2:
			IJ.error("Bad image format", "Image must contain at lease 2 channels!")
			return None
		if not self.pairs or \
			not self.methods:
			self.getOptionsDialog(self.imp)
		title = self.imp.title
		self.imp.title = title[:title.rfind('.')]
		return self.imp

	def getOptionsDialog(self, imp):
		thr_methods = ["None", "Default", "Huang", "Intermodes", "IsoData",  "Li", "MaxEntropy","Mean", "MinError(I)", "Minimum", "Moments", "Otsu", "Percentile", "RenyiEntropy", "Shanbhag" , "Triangle", "Yen"]
		gd = GenericDialog("Please select channels to collocalize")
		for i in range(1, imp.getNChannels() + 1):
			gd.addChoice("Threshold method for channel %i" % i, thr_methods, "None")
		gd.showDialog()
		if gd.wasCanceled():
			self.exit()
		channels = []
		for i in range(1, imp.getNChannels() + 1):
			method = gd.getNextChoice()
			self.methods.append(method)
			if method != "None":
				channels.append(i)
		for x in channels:
			for y in channels:
				if x < y:
					self.pairs.append((x, y))

	def processNextFile(self):
		if self.files:
			imageFile = self.files.pop(0)
			return self.processFile(imageFile)
		else:
			return False
			
	def processFile(self, imageFile):
		imp = self.openImage(imageFile)
		if imp is not None:
			cell = Cell(imp.NSlices, 1)
			self.cells = DelegateListModel([])
			self.cells.append(cell)
			self.showMainWindow(self.cells)
			if self.checkbox3D.isSelected():
				self.displayImage(imp)
			else:
				self.displayImage(imp, False)
				self.preview = self.previewImage(imp)
				self.displayImage(self.preview)
			return True
		else:
			return self.processNextFile()
	
	def displayImage(self, imp, show = True):
		imp.setDisplayMode(IJ.COMPOSITE)
		enhancer = ContrastEnhancer()
		enhancer.setUseStackHistogram(True)
		splitter = ChannelSplitter()
		for c in range(1, imp.getNChannels() + 1):
			imp.c = c
			enhancer.stretchHistogram(imp, 0.35)
		if show:
			imp.show()

	def previewImage(self, imp):
		roi = imp.getRoi()
		splitter = ChannelSplitter()
		channels = []
		for c in range(1, imp.getNChannels() + 1):
			channel = ImagePlus("Channel %i" % c, splitter.getChannel(imp, c))
			projector = ZProjector(channel)
			projector.setMethod(ZProjector.MAX_METHOD)
			projector.doProjection()
			channels.append(projector.getProjection())
		image = RGBStackMerge.mergeChannels(channels, False)
		image.title = imp.title + " MAX Intensity"
		image.luts = imp.luts
		imp.setRoi(roi)
		return image

	def getCroppedChannels(self, imp, cell):
		splitter = ChannelSplitter()
		imp.setRoi(None)
		if cell.mode3D:
			cropRoi = cell.getCropRoi()
		else:
			cropRoi = cell.roi
		if cropRoi is None:
			return None
		crop = cropRoi.getBounds()
		channels = []
		for c in range(1, imp.getNChannels() + 1):
			slices = ImageStack(crop.width, crop.height)
			channel = splitter.getChannel(imp, c)
			for z in range(1, channel.getSize() + 1):
				zslice = channel.getProcessor(z)
				zslice.setRoi(cropRoi)
				nslice = zslice.crop()
				if cell.mode3D:
					oroi = cell.slices[z - 1].roi	
				else:
					oroi = cell.roi
				if oroi is not None:
					roi = oroi.clone()
					bounds = roi.getBounds()
					roi.setLocation(bounds.x - crop.x, bounds.y - crop.y)
					nslice.setColor(Color.black)
					nslice.fillOutside(roi)
					slices.addSlice(nslice)
			channels.append(ImagePlus("Channel %i" % c, slices))
		return channels

	def getThreshold(self, imp, method):
		thresholder = Auto_Threshold()
		duplicator = Duplicator()
		tmp = duplicator.run(imp)
		return thresholder.exec(tmp, method, False, False, True, False, False, True)

	def getContainer(self, impA, impB):
		imgA = ImagePlusAdapter.wrap(impA)
		imgB = ImagePlusAdapter.wrap(impB)
		return DataContainer(imgA, imgB, 1, 1, "imageA", "imageB")

	def getManders(self, imp, cell):
	
		### Crop channels according to cell mask
		channels = self.getCroppedChannels(imp, cell)
		if channels is None:
			return None
			
		### Calculate channel thresholds
		thrs = []
		thrimps = []
		for c, method in enumerate(self.methods):
			if method != "None":
				thr, thrimp = self.getThreshold(channels[c], method)
			else:
				thr, thrimp = None, None
			thrs.append(thr)
			thrimps.append(thrimp)
		
		### Calculate manders colocalization
		manders = MandersColocalization()
		raws = []
		thrds = []
		for chA, chB in self.pairs:
			container = self.getContainer(channels[chA - 1], channels[chB - 1])
			img1 = container.getSourceImage1()
			img2 = container.getSourceImage2()
			mask = container.getMask()
			cursor = TwinCursor(img1.randomAccess(), img2.randomAccess(), Views.iterable(mask).localizingCursor())
			rtype = img1.randomAccess().get().createVariable()
			raw = manders.calculateMandersCorrelation(cursor, rtype)
			rthr1 = rtype.copy()
			rthr2 = rtype.copy()
			rthr1.set(thrs[chA - 1])
			rthr2.set(thrs[chB - 1])
			cursor.reset()
			thrd = manders.calculateMandersCorrelation(cursor, rthr1, rthr2, ThresholdMode.Above)
			raws.append(raw)
			thrds.append(thrd)
		
		return (channels, thrimps, thrs, raws, thrds)

	def saveMultichannelImage(self, title, channels, luts):
		tmp = RGBStackMerge.mergeChannels(channels, False)
		tmp.luts = luts
		saver = FileSaver(tmp)
		saver.saveAsTiffStack(self.outputDir + title + ".tif")
		tmp.close()

	def createMainWindow(self):
		self.frame = JFrame('Select cells and ROIs',
			defaultCloseOperation = JFrame.DISPOSE_ON_CLOSE
		)
		self.frame.setLayout(GridBagLayout())
		self.frame.addWindowListener(self)

		self.frame.add(JLabel("Cells"),
			GridBagConstraints(0, 0, 1, 1, 0, 0,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(5, 2, 2, 0), 0, 0
		))
		
		self.cellList = JList(DelegateListModel([]),
			selectionMode = ListSelectionModel.SINGLE_SELECTION,
			cellRenderer = MyRenderer(),
			selectedIndex = 0,
			valueChanged = self.selectCell
		)
		self.frame.add(JScrollPane(self.cellList),
			GridBagConstraints(0, 1, 1, 5, .5, 1,
				GridBagConstraints.CENTER, GridBagConstraints.BOTH,
				Insets(0, 2, 2, 0), 0, 0
		))

		self.frame.add(JButton('Add cell', actionPerformed = self.addCell),
			GridBagConstraints(1, 2, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))
    	
		self.frame.add(JButton('Remove cell', actionPerformed = self.removeCell),
			GridBagConstraints(1, 4, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 5, 0, 5), 0, 0
		))
		
		self.frame.add(JLabel("Slices"),
			GridBagConstraints(0, 6, 1, 1, 0, 0,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(5, 2, 2, 0), 0, 0
		))
		
		self.sliceList = JList(DelegateListModel([]),
			selectionMode = ListSelectionModel.SINGLE_SELECTION,
			cellRenderer = MyRenderer(),
			selectedIndex = 0,
			valueChanged = self.selectSlice
		)
		self.frame.add(JScrollPane(self.sliceList),
			GridBagConstraints(0, 7, 1, 5, .5, 1,
				GridBagConstraints.CENTER, GridBagConstraints.BOTH,
				Insets(0, 2, 2, 0), 0, 0
		))

		self.frame.add(JButton('Update ROI', actionPerformed = self.updateSlice),
			GridBagConstraints(1, 8, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))

		self.frame.add(JButton('Done', actionPerformed = self.doneSelecting),
			GridBagConstraints(1, 10, 1, 2, 0, .25,
				GridBagConstraints.CENTER, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))

		self.checkbox3D = JCheckBox('3D selection mode', True, actionPerformed=self.toggle3D)
		self.frame.add(self.checkbox3D,
			GridBagConstraints(0, 13, 2, 1, 0, 1,
				GridBagConstraints.WEST, GridBagConstraints.NONE,
				Insets(0, 0, 0, 0), 0, 0
		))

	def showMainWindow(self, cells = None):
		if cells is not None:
			self.cellList.model = cells
			if cells:
				self.cellList.selectedIndex = 0
		self.frame.pack()
		self.frame.visible = True

	def hideMainWindow(self):
		self.frame.visible = False

	def closeMainWindow(self):
		self.frame.dispose()

	def toggle3D(self, event):
		mode3D = self.checkbox3D.isSelected()
		if mode3D:
			self.sliceList.enabled = True
			if self.imp is not None:
				self.imp.show()
			if self.preview is not None:
				self.preview.hide()
		else:
			self.sliceList.enabled = False
			if self.preview is None:
				self.preview = self.previewImage(self.imp)
				self.displayImage(self.preview)
			else:
				self.preview.show()
			if self.imp is not None:
				self.imp.hide()
		selectedCell = self.cellList.selectedIndex
		if selectedCell >= 0:
			cell = self.cells[selectedCell]
			self.sliceList.model = cell.slices
			self.sliceList.selectedIndex = 0
		
	def addCell(self, event):
		size = len(self.cells)
		if (size > 0):
			last = self.cells[size - 1]
			n = last.n + 1
		else:
			n = 1
		self.cells.append(Cell(self.imp.NSlices, n))
		self.cellList.selectedIndex = size

	def removeCell(self, event):
		selected = self.cellList.selectedIndex
		if selected >= 0:
			self.cells.remove(self.cells[selected])
			if (selected >= 1):
				self.cellList.selectedIndex = selected - 1
			else:
				self.cellList.selectedIndex = 0

	def selectCell(self, event):
		selected = self.cellList.selectedIndex
		if selected >= 0:
			cell = self.cells[selected]
			self.sliceList.model = cell.slices
			self.sliceList.selectedIndex = 0
		else:
			self.sliceList.model = DelegateListModel([])
		if self.preview is not None:
			self.preview.setRoi(cell.roi)

	def selectSlice(self, event):
		selectedCell = self.cellList.selectedIndex
		selectedSlice = self.sliceList.selectedIndex
		if selectedCell >= 0 and selectedSlice >= 0:
			cell = self.cells[selectedCell]
			image = self.imp
			mode3D = self.checkbox3D.isSelected()
			if image is not None and cell is not None and mode3D:
				roi = cell.slices[selectedSlice].roi
				if (image.z - 1 != selectedSlice):
					image.z = selectedSlice + 1				
				image.setRoi(roi, True)
			if self.preview is not None and not mode3D:
				self.preview.setRoi(cell.roi, True)

	def updateSlice(self, event):
		if self.checkbox3D.isSelected():
			self.updateSlice3D(self.imp)
		else:
			self.updateSlice2D(self.preview)

	def updateSlice3D(self, imp):
		selectedCell = self.cellList.selectedIndex
		selectedSlice = self.sliceList.selectedIndex
		if selectedCell >= 0 and selectedSlice >= 0 and imp is not None:
			cell = self.cells[selectedCell]
			impRoi = imp.getRoi()
			if cell is not None and impRoi is not None:
				index = selectedSlice + 1
				roi = ShapeRoi(impRoi, position = index)
				cell.mode3D = True
				cell.name = "Cell %i (3D)" % cell.n
				cell.slices[selectedSlice].roi = roi
				if (index + 1 <= len(cell.slices)):
					imp.z = index + 1			
			self.cellList.repaint(self.cellList.getCellBounds(selectedCell, selectedCell))
			self.sliceList.repaint(self.sliceList.getCellBounds(selectedSlice, selectedSlice))

	def updateSlice2D(self, imp):
		selectedCell = self.cellList.selectedIndex
		if selectedCell >= 0 and imp is not None:
			cell = self.cells[selectedCell]
			impRoi = imp.getRoi()
			if cell is not None and impRoi is not None:
				roi = ShapeRoi(impRoi, position = 1)
				cell.mode3D = False
				cell.name = "Cell %i (2D)" % cell.n
				cell.roi = roi	
			self.cellList.repaint(self.cellList.getCellBounds(selectedCell, selectedCell))
	
	def imageOpened(self, imp):
		pass

	def imageClosed(self, imp):
		pass

	def imageUpdated(self, imp):
		if self.checkbox3D.isSelected():
			if imp is not None:
				selectedCell = self.cellList.selectedIndex
				selectedSlice = imp.z - 1
			if imp == self.imp and selectedSlice != self.sliceList.selectedIndex:
				self.sliceList.selectedIndex = selectedSlice

	def doneSelecting(self, event):
		oluts = self.imp.luts
		luts = []
		channels = []
		for c, method in enumerate(self.methods):
			if method != "None":
				luts.append(oluts[c])
				channels.append(c)
		for cell in self.cells:
			manders = self.getManders(self.imp, cell)
			if manders is not None:
				chimps, thrimps, thrs, raws, thrds = manders
				index = self.cells.index(cell) + 1
				title = "Cell_%i-" % index + self.imp.title
				self.saveMultichannelImage(title, chimps, oluts)
				title = "Cell_%i_thrd-" % index + self.imp.title
				self.saveMultichannelImage(title, thrimps, luts)
				self.results.incrementCounter()
				row = self.results.getCounter() - 1
				for i, thr in enumerate(thrs):
					if thr is not None:
						self.results.setValue("Threshold %i" % (i + 1), row, int(thr))
				for i, pair in enumerate(self.pairs):
					self.results.setValue("%i-%i M1 raw" % pair, row, float(raws[i].m1))
					self.results.setValue("%i-%i M2 raw" % pair, row, float(raws[i].m2))
					self.results.setValue("%i-%i M1 thrd" % pair, row, float(thrds[i].m1))
					self.results.setValue("%i-%i M2 thrd" % pair, row, float(thrds[i].m2))
		self.closeImage()
		if not self.processNextFile():
			print "All done - happy analysis!"
			self.results.show("Manders collocalization results")
			self.exit()

	def windowClosing(self, e):
		print "Closing plugin - BYE!!!"
		self.exit()

	def exit(self):
		ImagePlus.removeImageListener(self)
		self.closeImage()
		self.closeMainWindow()
class MenueFrame(object):
   def __init__(self):
      self.mainDir = ""
   
      self.frame = JFrame("Dots Quality Check", size=(250,300))
      self.frame.setLocation(20,120)
      self.Panel = JPanel(GridLayout(0,1))
      self.frame.add(self.Panel)

      self.openNextButton = JButton('Open Next Random',actionPerformed=openRandom)
      self.Panel.add(self.openNextButton)
      
      self.saveButton = JButton('Save',actionPerformed=save)
      self.saveButton.setEnabled(False)
      self.Panel.add(self.saveButton)

      self.cropButton = JButton('Crop values from here', actionPerformed=cropVals)
      self.Panel.add(self.cropButton)

      self.DiscardButton = JButton('Discard cell', actionPerformed=discardCell)
      self.DiscardButton.setEnabled(True)
      self.Panel.add(self.DiscardButton)

      self.quitButton = JButton('Quit script',actionPerformed=quit)
      self.Panel.add(self.quitButton)

      annoPanel = JPanel()
      #add gridlayout
      wtRButton = JRadioButton("wt", actionCommand="wt")
      defectRButton = JRadioButton("Defect", actionCommand="defect")
      annoPanel.add(wtRButton)
      annoPanel.add(defectRButton)
      self.aButtonGroup = ButtonGroup()
      self.aButtonGroup.add(wtRButton)
      self.aButtonGroup.add(defectRButton)
      
      self.Panel.add(annoPanel)

      self.ProgBar = JProgressBar()
      self.ProgBar.setStringPainted(True)
      self.ProgBar.setValue(0)
      self.Panel.add(self.ProgBar)

      self.pathLabel = JLabel("-- No main directory chosen --")
      self.pathLabel.setHorizontalAlignment( SwingConstants.CENTER )
      self.Panel.add(self.pathLabel)

      
      WindowManager.addWindow(self.frame)
      self.show()

   def show(self):
      self.frame.visible = True

   def getFrame(self):
      return self.frame

   def setSaveActive(self):
      self.saveButton.setEnabled(True)
      self.show()

   def setSaveInactive(self):
      self.saveButton.setEnabled(False)
      self.show()

   def setMainDir(self, path):
      self.mainDir = path
      self.pathLabel.setText("MainDir: " + os.path.basename(os.path.split(self.mainDir)[0]))

   def getMainDir(self):
      return self.mainDir

   def setProgBarMax(self, maximum):
      self.ProgBar.setMaximum(maximum)

   def setProgBarVal(self, value):
      self.ProgBar.setValue(value)

   def close():
      WindowManager.removeWindow(self.frame)
      self.frame.dispose()     
示例#57
0
def main():
	
	binNaviProxy = StandAlone.getPluginInterface()
	binNaviProxy.databaseManager.addDatabase("","com.mysql.jdbc.Driver","localhost","BINNAVI1","binnavi","binnavi",False,False)
	db=binNaviProxy.databaseManager.databases[0]
	db.connect()
	db.load()
	mods=db.getModules()
	
	### initiate dialogBox to setect the module that should be used.
	
	######################################################
	
	
	frame = JFrame('BinNavi Module Selector',layout=BorderLayout(),		
				defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
				size = (1500, 800)
			)
	frame2 = JFrame('Function Selector',layout=BorderLayout(),		
				defaultCloseOperation = JFrame.EXIT_ON_CLOSE,
				size = (30, 30)
			)
			
	frame2.setFocusableWindowState(False)
	frame2.setFocusable(False)
	frame2.setAlwaysOnTop(False)
	#convert the module list into the string to be used in the TextBox.
	textTemp = map((lambda x,y:"[%d]%s"%(x,y)),range(len(mods)),mods) 
	textStr=''.join(textTemp)

	tx=JTextArea(textStr)
	tx.setLineWrap(True);
	tx.setWrapStyleWord(True);
	frame.add(tx,BorderLayout.PAGE_START)
	frame.visible = True
	modInd = JOptionPane.showInputDialog(frame2, "Enter the index of the chosen module", 
			 "Module selector");
	
	#Open the module returned by the index 
	bfname=mods[int(modInd)] # this modules correxponds to the chosen module
	bfname.load()
	funcViews=bfname.views
	#textTemp2 = ["[%d]%s"%(i,j) for i in range(len(funcViews)) for j in funcViews]
	textTemp2=map((lambda x,y:"[%d]%s"%(x,y.toString()[5:18])),range(len(funcViews)),funcViews)
	textStr1=''.join(textTemp2)
	## remove the older text from the frame view
	frame.remove(tx)
	frame.update(frame.getGraphics())
	frame.visible = False
	## create a new textArea with the string made from all the functions' name
	txStr=JTextArea(textStr1)
	#tx.setsrcollOffset(20)
	txStr.setLineWrap(True);
	txStr.setWrapStyleWord(True);
	frame.add(txStr,BorderLayout.PAGE_START)
	frame.update(frame.getGraphics())
	frame.visible = True
	funcInd = JOptionPane.showInputDialog(frame2, "Enter the index of the function", 
			 "Function selector");
   
 ######################################################
	
	
	bffunc=bfname.views[int(funcInd)] #this is the view of the buildfname function
	bffunc.load()
	
	frame2.setVisible(False)
	dispose(frame2)
	
	bfReil=bffunc.getReilCode() # this is the REIL code of the function
	bfReilGraph=bfReil.getGraph()
			
	instGraph = InstructionGraph.create(bfReilGraph)
	time.clock()
	results=doAnalysis(instGraph)
	totalTime=time.clock()
	#print "resultsLen", len([r for r in results])
			
	print "**** printing results *******\n"
	print "Total time:", totalTime, '\n'
	numNode=0
	for n in instGraph:
		numNode+=numNode
		
		nIn=list(results.getState(n).inVal)
		nIn.sort(key=itemgetter(0))
		nOut=list(results.getState(n).out)
		nOut.sort(key=itemgetter(0))
		print '@@ ',n.getInstruction(),'\n'
		print '\t In', nIn, '\n'
		print '\t OUT', nOut, '\n'
		print '\t memory: ',results.getState(n).memoryWritten, '\n'
	print "++++ Total instructions: %d +++++\n"%numNode		 
	#finally close the view of the function
	bffunc.close()
	#print bffunc.isLoaded()
	#junky=raw_input("function closed. enter any charater")
	


	print "Done! Closing the module selector window"
	frame.setVisible(False)
	dispose(frame)
示例#58
0
vdata = mdi.getGridData('V')

#---- Create wind vector layer from the U/V grid data
layer = DrawMeteoData.createGridVectorLayer(udata, vdata,  'UV_Vector', True)
#layer = DrawMeteoData.createGridBarbLayer(udata, vdata,  'UV_Barb', True)
#layer = DrawMeteoData.createStreamlineLayer(udata, vdata, 'Z_Streamline', True)

#---- Add layer
mapFrame.addLayer(layer)

#--- Move pressure layer to bottom
mapFrame.moveLayer(layer, 0)

#---- Add title
title = mapLayout.addText('MeteoInfo script demo', 350, 30, 'Arial', 16)

#---- Add wind arrow
windArrow = mapLayout.addWindArrow(660, 420)

#---- Zoom layout map
print 'Zoom layout map...'
mapLayout.getActiveLayoutMap().zoomToExtentLonLatEx(Extent(70, 140, 15, 55))

#---- Set mapframe
mapFrame.setGridXDelt(10)
mapFrame.setGridYDelt(10)

frame = JFrame('MeteoInfo Script Sample', size = (800, 600))
frame.add(mapLayout)
frame.visible = True
print 'Finished!'
示例#59
0
class GUI():
    def __init__(self):
        self.frame = JFrame('Phone status twitter')
        self.frame.defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
        self.asteriskLoginPanel = gui.AsteriskLoginPanel(buttonAction=self.loginToAsterisk)
        self.asteriskLoginPanel.render()
        self.frame.add(self.asteriskLoginPanel)
        self.asteriskLoginPanel.getRootPane().setDefaultButton(self.asteriskLoginPanel.login)
        self.frame.pack()
        self.frame.visible = True

    def renderTwitterLoginPanel(self):
        '''Render on the frame the login panel with the fields needed to
        authenticate with the Twitter API.'''
        self.twitterLoginPanel = JPanel(GridLayout(0,2))
        self.frame.add(self.twitterLoginPanel)
        
        self.twitterLoginPanel.setBorder(BorderFactory.createTitledBorder('Twitter account information'))

        self.twitterLoginField = extragui.EnhancedTextField('asterisk-jython', 15)
        self.twitterLoginPanel.add(JLabel('Username:'******'password', 15)
        self.twitterLoginPanel.add(JLabel('Password:'******'Log in', actionPerformed=self.loginToTwitter)
        self.twitterLoginPanel.add(self.twitterLoginButton)
        self.twitterLoginPanel.getRootPane().setDefaultButton(self.twitterLoginButton)

        self.twitterLoginStatusLabel = JLabel('Awaiting information...')
        self.twitterLoginPanel.add(self.twitterLoginStatusLabel)

    def renderMainPanel(self):
        '''Render on the frame the main panel with a status label'''
        self.mainPanel = JPanel(GridLayout(0,2))
        self.frame.add(self.mainPanel)

        self.mainPanel.setBorder(BorderFactory.createTitledBorder('Application status'))

        self.mainPanel.add(JLabel('Status:'))
        self.statusLabel = JTextField('Running...', 15)
        self.statusLabel.editable = False
        self.mainPanel.add(self.statusLabel)

    def loginToAsterisk(self, event):
        '''Execute the login procedure to the Asterisk Manager interface'''
        self.manager = PhoneStatusListener(self.asteriskLoginPanel.hostname.text, \
                                            self.asteriskLoginPanel.username.text, \
                                            self.asteriskLoginPanel.password.text, \
                                            self.asteriskLoginPanel.extension.text)
        try:
            self.manager.addStatusUpdater(self.statusUpdater)
            self.manager.start()
            self.asteriskLoginPanel.visible = False
            self.renderTwitterLoginPanel()
            self.twitterLoginField.requestFocusInWindow()
            self.frame.pack()
        except:
            self.asteriskLoginPanel.status.text = "Unable to authenticate"

    def loginToTwitter(self, event):
        '''Execute the login procedure to the Twitter platform'''
        try:
            self.twitter = twitter.Api(username=self.twitterLoginField.text, \
                                        password=self.twitterPasswordField.text)
            self.twitter.GetUser(self.twitterLoginField.text)
            self.twitterLoginPanel.visible = False
            self.renderMainPanel()
            self.frame.pack()
        except:
            self.twitterLoginStatusLabel.text = "Unable to authenticate"

    def statusUpdater(self, update):
        self.statusLabel.text = update
        self.twitter.PostUpdate(update)