Esempio n. 1
0
def makeUI(model):
    table = JTable(model)
    jsp = JScrollPane(table)
    regex_label = JLabel("Search: ")
    regex_field = JTextField(20)
    top = JPanel()
    top.add(regex_label)
    top.add(regex_field)
    top.setLayout(BoxLayout(top, BoxLayout.X_AXIS))
    base_path_label = JLabel("Base path:")
    base_path_field = JTextField(50)
    bottom = JPanel()
    bottom.add(base_path_label)
    bottom.add(base_path_field)
    bottom.setLayout(BoxLayout(bottom, BoxLayout.X_AXIS))
    all = JPanel()
    all.add(top)
    all.add(jsp)
    all.add(bottom)
    all.setLayout(BoxLayout(all, BoxLayout.Y_AXIS))
    frame = JFrame("File paths")
    frame.getContentPane().add(all)
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
    frame.addWindowListener(Closing())
    frame.pack()
    frame.setVisible(True)
    # Listeners
    regex_field.addKeyListener(EnterListener(table, model, frame))
    table.addMouseListener(RowClickListener(base_path_field))
    #
    return model, table, regex_field, frame
Esempio n. 2
0
def tree():
  """
  tree(xmlfile="dsm2.xml")
    creates a tree view on a given xml file of dsm2 input data
  """
  tv = TreeViewer()
  mp2 = JPanel()
  mp2.setLayout(BorderLayout())
  tf = JTextField("dsm2.inp")
  pb = JButton("parse")
  mp2.add(tf,BorderLayout.CENTER)
  mp2.add(pb,BorderLayout.EAST)
  class ParseListener(ActionListener):
    def __init__(self,tf,tv,fr):
      self.tf = tf
      self.tv = tv
      self.fr = fr
    def actionPerformed(self,evt):
      dsm2file = self.tf.getText()
      parser = DSM2Parser(dsm2file)
      self.tv.xdoc = parser.dsm2_data.toXml()
      self.fr.getContentPane().add(self.tv.gui(),BorderLayout.CENTER)
      self.fr.pack()
      self.fr.setVisible(1)
  fr = JFrame()
  fr.setTitle("DSM2Tree")
  fr.setLocation(100,100)
  fr.setSize(600,60)
  fr.getContentPane().setLayout(BorderLayout())
  fr.getContentPane().add(mp2,BorderLayout.NORTH)
  al = ParseListener(tf,tv,fr)
  pb.addActionListener(al)
  fr.pack()
  fr.setVisible(1)
Esempio n. 3
0
 def gui_open(path):
     label = JLabel(ImageIcon(ImageIO.read(File(URL(path).getFile()))))
     frame = JFrame()
     frame.getContentPane().add(label)
     frame.pack()
     frame.setLocation(200, 200)
     frame.setVisible(True)
Esempio n. 4
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)
Esempio n. 5
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)
Esempio n. 6
0
 def display(self):
     colnames = ['file', 'line']
     table = JTable(self.results, colnames)
     frame = JFrame("%i Results" % len(self.results))
     frame.getContentPane().add(table)
     frame.size = 400, 300
     frame.defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
     frame.visible = True
Esempio n. 7
0
    def createAndShowGUI(self):
        frame = JFrame("HelloWorldSwing")
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

        label = JLabel("Hello World")
        frame.getContentPane().add(label)

        frame.pack()
        frame.setVisible(True)
Esempio n. 8
0
def makeUI(model):
    # Components:
    table = JTable(model)
    jsp = JScrollPane(table)
    regex_label = JLabel("Search: ")
    regex_field = JTextField(20)
    base_path_label = JLabel("Base path:")
    base_path_field = JTextField(50)
    if base_path is not None:
        base_path_field.setText(base_path)
    # Panel for all components
    all = JPanel()
    all.setBorder(EmptyBorder(20, 20, 20, 20))
    layout, c = GridBagLayout(), GC()
    all.setLayout(layout)
    # First row: label and regex text field
    add(all, regex_label, gridx=0, gridy=0)  # with default constraints
    add(all, regex_field, gridx=1, gridy=0, fill=GC.HORIZONTAL, weightx=1.0)
    # Second row: the table
    add(all,
        jsp,
        gridx=0,
        gridy=1,
        fill=GC.BOTH,
        gridwidth=2,
        weightx=1.0,
        weighty=1.0)  # full weights so it stretches when resizing
    # Third row: the base path
    add(all, base_path_label, gridx=0, gridy=2)
    add(all,
        base_path_field,
        gridx=1,
        gridy=2,
        fill=GC.HORIZONTAL,
        weightx=1.0)
    # Window frame
    frame = JFrame("File paths")
    frame.getContentPane().add(all)
    #frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
    frame.addWindowListener(Closing())
    frame.pack()
    frame.setVisible(True)
    # Listeners
    regex_field.addKeyListener(EnterListener(table))
    table.addMouseListener(RowClickListener(base_path_field))
    al = ArrowListener(table, regex_field)
    table.addKeyListener(al)
    regex_field.addKeyListener(al)
    # Instead of a KeyListener, use the input vs action map
    table.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
                            "enter")
    table.getActionMap().put("enter", OpenImageFromTableCell())
    #
    return model, table, regex_field, frame
    def run(self):
        frame = JFrame('ProgressMonitor',
                       size=(280, 125),
                       locationRelativeTo=None,
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
        frame.getContentPane().setBorder(
            BorderFactory.createEmptyBorder(20, 20, 20, 20))

        panel = JPanel()
        self.button = panel.add(JButton('Start', actionPerformed=self.start))
        frame.add(panel, BorderLayout.NORTH)
        frame.setVisible(1)
def readSVG(svgPath):
	#parser = XMLResourceDescriptor.getXMLParserClassName()
	#f = SAXSVGDocumentFactory(parser)
	#print(svgPath)
	#doc = f.createDocument(svgPath.toURI().toString())
	#print(doc)
	svgCanvas = JSVGCanvas()
	svgCanvas.setURI(svgPath.toURI().toString())
	f = JFrame('SVG image', size=(1000, 1000), locationRelativeTo=None)
	p = JPanel()
	p.add(svgCanvas)
	f.getContentPane().add(p)
	f.setVisible(True)
def show_plot_in_frame(mainPanel):
    """
    embeds panel containing plots in a closable frame
    clears the panel background to white 
    """
    fr=JFrame()
    fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    fr.getContentPane().add(mainPanel)
    fr.setSize(1100,850);
    mainPanel.setSize(1100,850);
    mainPanel.setBackground(Color.WHITE);
    fr.show();
    return fr
Esempio n. 12
0
def show_plot_in_frame(mainPanel):
    """
    embeds panel containing plots in a closable frame
    clears the panel background to white 
    """
    fr = JFrame()
    fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
    fr.getContentPane().add(mainPanel)
    fr.setSize(1100, 850)
    mainPanel.setSize(1100, 850)
    mainPanel.setBackground(Color.WHITE)
    fr.show()
    return fr
Esempio n. 13
0
    def run(self):
        frame = JFrame('BlueLabel')  # Create a JFrame with a title
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)

        Label = JLabel()  # Create an empty label
        Label.setOpaque(1)  # Must be opaque for color to be seen
        Label.setBackground(Color.BLUE)  # Make the label blue
        Label.setPreferredSize(Dimension(200, 200))

        frame.getContentPane().add(Label)  # Add the label to the content pane

        frame.pack()  # Size frame to display the contents
        frame.setVisible(1)  # Finally, make the frame visible
Esempio n. 14
0
def showTable(rows,
              title="Table",
              column_names=None,
              dataType=Number,
              width=400,
              height=500,
              showTable=True,
              windowClosing=None,
              onCellClickFn=None,
              onRowClickFn=None):
    """
     rows: list of lists of numbers.
     title: for the JFrame
     column_names: list of strings, or None
     width: defaults to 400 px
     height: defaults to 500 px
     showTable: whether to show the JFrame.
     windowClosing: an optional function to execute when the table's JFrame is closed.
     onClickCellFn: an optional function to execute when a table's cell is clicked, and receiving 3 args: row index, col index, cell value.
     onRowCellFn: an optinal function to execute when a table's row is clicked, and receiving as args the whole row.
     
     return: a tuple with the JTable and the JFrame
  """
    table_data = DataTable(rows,
                           column_names=column_names,
                           onCellClickFn=onCellClickFn,
                           onRowClickFn=onRowClickFn)
    table = JTable(table_data)
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION)
    #table.setAutoCreateRowSorter(True) # to sort the view only, not the data in the underlying TableModel
    sorter = TableRowSorter(table_data)
    sorter.setComparator(0, Comparator.naturalOrder())
    sorter.setComparator(1, Comparator.naturalOrder())
    sorter.setComparator(2, Comparator.naturalOrder())
    table.setRowSorter(sorter)

    frame = JFrame(title) if windowClosing is None else JFrame(
        title, windowClosing=windowClosing)
    jsp = JScrollPane(table)
    jsp.setMinimumSize(Dimension(width, height))
    frame.getContentPane().add(jsp)

    def show():
        frame.pack()
        frame.setVisible(True)

    if showTable:
        SwingUtilities.invokeLater(show)

    return table, frame
Esempio n. 15
0
    def __init__(self, title, display, panel):
        from java.awt import Toolkit
        from javax.swing import JFrame
        self.display = display

        frame = JFrame(title, windowClosing=self.desty)
        frame.getContentPane().add(panel)
        frame.pack()
        frame.invalidate()

        fSize = frame.getSize()
        screensize = Toolkit.getDefaultToolkit().getScreenSize()
        frame.setLocation((screensize.width - fSize.width) / 2,
                          (screensize.height - fSize.height) / 2)
        frame.setVisible(1)
Esempio n. 16
0
  def __init__(self, title, display, panel):
    from java.awt import Toolkit
    from javax.swing import JFrame
    self.display = display

    frame = JFrame(title, windowClosing=self.desty)
    frame.getContentPane().add(panel)
    frame.pack()
    frame.invalidate()

    fSize = frame.getSize()
    screensize = Toolkit.getDefaultToolkit().getScreenSize()
    frame.setLocation((screensize.width - fSize.width)/2,
                      (screensize.height - fSize.height)/2)
    frame.setVisible(1)
Esempio n. 17
0
class _AccountAdder:
    def __init__(self, contactslist):
        self.contactslist = contactslist
        self.mainframe = JFrame("Add New Contact")
        self.account = JComboBox(self.contactslist.clientsByName.keys())
        self.contactname = JTextField()
        self.buildpane()

    def buildpane(self):
        buttons = JPanel()
        buttons.add(JButton("OK", actionPerformed=self.add))
        buttons.add(JButton("Cancel", actionPerformed=self.cancel))

        acct = JPanel(GridLayout(1, 2), doublebuffered)
        acct.add(JLabel("Account"))
        acct.add(self.account)

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
        mainpane.add(self.contactname)
        mainpane.add(acct)
        mainpane.add(buttons)
        self.mainframe.pack()
        self.mainframe.show()

    #action listeners
    def add(self, ae):
        acct = self.contactslist.clientsByName[self.account.getSelectedItem()]
        acct.addContact(self.contactname.getText())
        self.mainframe.dispose()

    def cancel(self, ae):
        self.mainframe.dispose()
Esempio n. 18
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)
Esempio n. 19
0
class _AccountAdder:
    def __init__(self, contactslist):
        self.contactslist = contactslist
        self.mainframe = JFrame("Add New Contact")
        self.account = JComboBox(self.contactslist.clientsByName.keys())
        self.contactname = JTextField()
        self.buildpane()

    def buildpane(self):
        buttons = JPanel()
        buttons.add(JButton("OK", actionPerformed=self.add))
        buttons.add(JButton("Cancel", actionPerformed=self.cancel))

        acct = JPanel(GridLayout(1, 2), doublebuffered)
        acct.add(JLabel("Account"))
        acct.add(self.account)

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
        mainpane.add(self.contactname)
        mainpane.add(acct)
        mainpane.add(buttons)
        self.mainframe.pack()
        self.mainframe.show()

    #action listeners
    def add(self, ae):
        acct = self.contactslist.clientsByName[self.account.getSelectedItem()]
        acct.addContact(self.contactname.getText())
        self.mainframe.dispose()

    def cancel(self, ae):
        self.mainframe.dispose()
Esempio n. 20
0
class ShowImageViewer:
    def __init__(self):
        self.frame = JFrame("Display Image")

        btn = JButton("Switch",actionPerformed=self.switchPic)
        #self.frame.getContentPane().add(btn)
        self.switchPic('/home/jack/Desktop/mgarvin.jpg')
        self.frame.setSize(500,500)
        self.frame.setVisible(True)

    def callSwitchPic(self,event):
        self.switchPic('/home/jack/Desktop/mteam.jpg')
    
    def switchPic(self,image):
        panel = ShowImage(image)
        self.frame.getContentPane().add(panel)        
Esempio n. 21
0
File: graph.py Progetto: visad/visad
class myAnimFrame:
    """
  Supporting class for animations.
  """
    def desty(self, event):
        self.display.destroy()
        self.frame.dispose()

    def __init__(self, display, widget, width, height, title):
        from javax.swing import JFrame, JPanel
        from java.awt import BorderLayout, FlowLayout
        self.display = display
        self.panel = JPanel(BorderLayout())
        self.panel2 = JPanel(FlowLayout())
        self.panel2.add(widget)
        self.panel.add("North", self.panel2)
        self.panel.add("Center", self.display.getComponent())

        self.frame = JFrame(title, windowClosing=self.desty)
        self.pane = self.frame.getContentPane()
        self.pane.add(self.panel)

        self.frame.setSize(width, height)
        self.frame.pack()
        self.frame.show()
 def run(self):
     frame = JFrame('ComponentEventDemo',
                    locationRelativeTo=None,
                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
     cp = frame.getContentPane()
     cp.setLayout(BorderLayout())
     self.display = JTextArea(editable=0,
                              font=Font('Courier', Font.PLAIN, 12))
     myListener = listener(self.display)
     frame.addComponentListener(myListener)
     scrollPane = JScrollPane(self.display,
                              preferredSize=Dimension(350, 210))
     cp.add(scrollPane, BorderLayout.CENTER)
     panel = JPanel(BorderLayout(), componentListener=myListener)
     self.button = JButton('Clear',
                           actionPerformed=self.clear,
                           componentListener=myListener)
     panel.add(self.button, BorderLayout.CENTER)
     visible = JCheckBox('Button visible',
                         selected=1,
                         itemStateChanged=self.showHide,
                         componentListener=myListener)
     panel.add(visible, BorderLayout.PAGE_END)
     cp.add(panel, BorderLayout.PAGE_END)
     frame.pack()
     frame.setVisible(1)
Esempio n. 23
0
    def run(self):
        frame = JFrame('Console timeout',
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        #-----------------------------------------------------------------------
        # The frame (i.e., it's ContentPane) should use a vertically aligned
        # BoxLayout layout manager (i.e., along the Y_AXIS)
        #-----------------------------------------------------------------------
        cp = frame.getContentPane()
        cp.setLayout(BoxLayout(cp, BoxLayout.Y_AXIS))

        #-----------------------------------------------------------------------
        # The JTextField will be preceeded, and followed by JLabel components
        # identifying the value being displayed, and the associated time units.
        # However, we want them displayed horizontally, so we put them into a
        # single JPanel instance using a FlowLayout layout manager
        #-----------------------------------------------------------------------
        input = JPanel(layout=FlowLayout())
        input.add(JLabel('Timeout:'))
        self.text = JTextField(3, actionPerformed=self.update)
        input.add(self.text)
        self.text.setText(getTimeout())
        input.add(JLabel('minutes'))
        cp.add(input)

        #-----------------------------------------------------------------------
        # Then, we add a message area beneath
        #-----------------------------------------------------------------------
        self.msg = cp.add(JLabel())

        frame.setSize(290, 100)
        frame.setVisible(1)
Esempio n. 24
0
class myAnimFrame:
  """
  Supporting class for animations.
  """
  def desty(self, event):
    self.display.destroy()
    self.frame.dispose()

  def __init__(self, display, widget, width, height, title):
    from javax.swing import JFrame, JPanel
    from java.awt import BorderLayout, FlowLayout
    self.display = display
    self.panel = JPanel(BorderLayout())
    self.panel2 = JPanel(FlowLayout())
    self.panel2.add(widget)
    self.panel.add("North", self.panel2)
    self.panel.add("Center",self.display.getComponent())

    self.frame = JFrame(title, windowClosing=self.desty)
    self.pane = self.frame.getContentPane()
    self.pane.add(self.panel)

    self.frame.setSize(width,height)
    self.frame.pack()
    self.frame.show()
Esempio n. 25
0
class ConversationWindow(Conversation):
    """A GUI window of a conversation with a specific person"""
    def __init__(self, person, chatui):
        """ConversationWindow(basesupport.AbstractPerson:person)"""
        Conversation.__init__(self, person, chatui)
        self.mainframe = JFrame("Conversation with "+person.name)
        self.display = JTextArea(columns=100,
                                 rows=15,
                                 editable=0,
                                 lineWrap=1)
        self.typepad = JTextField()
        self.buildpane()
        self.lentext = 0

    def buildpane(self):
        buttons = JPanel(doublebuffered)
        buttons.add(JButton("Send", actionPerformed=self.send))
        buttons.add(JButton("Hide", actionPerformed=self.hidewindow))

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
        mainpane.add(JScrollPane(self.display))
        self.typepad.actionPerformed = self.send
        mainpane.add(self.typepad)
        mainpane.add(buttons)

    def show(self):
        self.mainframe.pack()
        self.mainframe.show()

    def hide(self):
        self.mainframe.hide()

    def sendText(self, text):
        self.displayText("\n"+self.person.client.name+": "+text)
        Conversation.sendText(self, text)

    def showMessage(self, text, metadata=None):
        self.displayText("\n"+self.person.name+": "+text)

    def contactChangedNick(self, person, newnick):
        Conversation.contactChangedNick(self, person, newnick)
        self.mainframe.setTitle("Conversation with "+newnick)

    #GUI code
    def displayText(self, text):
        self.lentext = self.lentext + len(text)
        self.display.append(text)
        self.display.setCaretPosition(self.lentext)

    #actionlisteners
    def hidewindow(self, ae):
        self.hide()

    def send(self, ae):
        text = self.typepad.getText()
        self.typepad.setText("")
        if text != "" and text != None:
            self.sendText(text)
Esempio n. 26
0
def geom_viewer(dsm2file = "dsm2.inp"):
  """
  geom_viewer(dsm2file = "dsm2.inp")
  starts off a dsm2 geometry viewer for dsm2 input data
  Irregular xsections are plotted if available otherwise
  regular xsections are plotted.
  """
  dgv = DSM2GeomViewer(dsm2file)
  mp = dgv.gui()
  fr = JFrame()
  fr.setTitle('Geom Viewer')
  fr.getContentPane().add(mp)
  fr.setLocation(300,100)
  fr.pack()
  sz = fr.getSize()
  fr.setSize(250,sz.height)
  fr.setVisible(1)
Esempio n. 27
0
    def run(self):
        frame = JFrame('TabbedPaneDemo',
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        self.addTabs(frame.getContentPane())

        frame.setSize(300, 125)
        frame.setVisible(1)
Esempio n. 28
0
    def run(self):
        frame = JFrame('GridBagLayout2',
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        self.addComponents(frame.getContentPane())

        frame.setSize(410, 190)
        frame.setVisible(1)
Esempio n. 29
0
    def run(self):
        frame = JFrame('MainFrame', defaultCloseOperation = JFrame.DISPOSE_ON_CLOSE)
        self.addButtons(frame.getContentPane())
        frame.size = (300, 175)
        frame.visible = 1 

        self.frame = frame
        self.startTimerTask()
Esempio n. 30
0
    def run(self):
        frame = JFrame('TableSelection3',
                       locationRelativeTo=None,
                       defaultCloseOperation=JFrame.EXIT_ON_CLOSE)

        self.addTabs(frame.getContentPane())

        frame.setSize(500, 200)
        frame.setVisible(1)
Esempio n. 31
0
class ConversationWindow(Conversation):
    """A GUI window of a conversation with a specific person"""
    def __init__(self, person, chatui):
        """ConversationWindow(basesupport.AbstractPerson:person)"""
        Conversation.__init__(self, person, chatui)
        self.mainframe = JFrame("Conversation with " + person.name)
        self.display = JTextArea(columns=100, rows=15, editable=0, lineWrap=1)
        self.typepad = JTextField()
        self.buildpane()
        self.lentext = 0

    def buildpane(self):
        buttons = JPanel(doublebuffered)
        buttons.add(JButton("Send", actionPerformed=self.send))
        buttons.add(JButton("Hide", actionPerformed=self.hidewindow))

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
        mainpane.add(JScrollPane(self.display))
        self.typepad.actionPerformed = self.send
        mainpane.add(self.typepad)
        mainpane.add(buttons)

    def show(self):
        self.mainframe.pack()
        self.mainframe.show()

    def hide(self):
        self.mainframe.hide()

    def sendText(self, text):
        self.displayText("\n" + self.person.client.name + ": " + text)
        Conversation.sendText(self, text)

    def showMessage(self, text, metadata=None):
        self.displayText("\n" + self.person.name + ": " + text)

    def contactChangedNick(self, person, newnick):
        Conversation.contactChangedNick(self, person, newnick)
        self.mainframe.setTitle("Conversation with " + newnick)

    #GUI code
    def displayText(self, text):
        self.lentext = self.lentext + len(text)
        self.display.append(text)
        self.display.setCaretPosition(self.lentext)

    #actionlisteners
    def hidewindow(self, ae):
        self.hide()

    def send(self, ae):
        text = self.typepad.getText()
        self.typepad.setText("")
        if text != "" and text != None:
            self.sendText(text)
Esempio n. 32
0
    def run( self ) :
        frame = JFrame(
           'GridBagLayout0',
            defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        )

        self.addComponents( frame.getContentPane() )

        frame.setSize( 300, 150 )      # Display grid & some space
        frame.setVisible( 1 )
Esempio n. 33
0
 def run(self):
     frame = JFrame('Check Boxes',
                    layout=FlowLayout(),
                    size=(250, 100),
                    defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
     cp = frame.getContentPane()
     self.addCB(cp, 'Yes')
     self.addCB(cp, 'No')
     self.addCB(cp, 'Maybe')
     self.label = frame.add(JLabel('Nothing selected'))
     frame.setVisible(1)
Esempio n. 34
0
 def app(self, label="InQL Scanner"):
     frame = JFrame(label)
     frame.setForeground(Color.black)
     frame.setBackground(Color.lightGray)
     cp = frame.getContentPane()
     cp.add(self.this)
     frame.pack()
     frame.setVisible(True)
     frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
     while frame.isVisible():
         time.sleep(1)
Esempio n. 35
0
    def run( self ) :
        frame = JFrame(
           'GridBagLayout4',
            defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        )

        self.addComponents( frame.getContentPane() )

#       frame.pack()
#       print frame.getSize()
        frame.setSize( 475, 210 )
        frame.setVisible( 1 )
Esempio n. 36
0
class ApplicationTestCase(unittest.TestCase):
	def setUp(self):
		Robot().mouseMove(800, 600)
		self.launch_app()
		self.app = ApplicationTestApp()

	def tearDown(self):
		self.frame.setVisible(False)
		self.frame.dispose()

	def launch_app(self):
		self.frame = JFrame("Test Window", defaultCloseOperation=JFrame.EXIT_ON_CLOSE)
		pane = self.frame.getContentPane()
		layout = SpringLayout()
		pane.setLayout(layout)
		label = JLabel("Test Label")
		pane.add(label)
		layout.putConstraint(SpringLayout.WEST, label, 20, SpringLayout.WEST, pane)
		layout.putConstraint(SpringLayout.NORTH, label, 20, SpringLayout.NORTH, pane)
		self.frame.pack()
		self.frame.setVisible(True)
		self.frame.setSize(800, 600)

	def test_init_window(self):
		window = self.app.init_window(ApplicationTestWindow)
		self.assertNotEqual(window, None)
		self.assertTrue(isinstance(window, ApplicationTestWindow))
		self.assertEqual((window.region.getW(), window.region.getH()), (800, 600))

	def test_create_image_folders(self):
		path = os.path.join('images', 'application_test_window', 'test_label')
		shutil.move(os.path.join(path, 'enabled.png'), os.path.join('images', '.enabled.png.tmp'))
		shutil.rmtree(os.path.join('images', 'application_test_window'))
		self.app.create_image_folders()
		self.assertTrue(os.path.exists(path))
		shutil.move(os.path.join('images', '.enabled.png.tmp'), os.path.join(path, 'enabled.png'))

	# TODO: test_capture_screenshots
	# TODO: test_open

	def test_find_focused_window(self):
		window = self.app.find_focused_window()
		self.assertNotEqual(window, None)
		self.assertTrue(isinstance(window, ApplicationTestWindow))

	def test_focused_window(self):
		before_time = time.time()
		window = self.app.focused_window(10)
		after_time = time.time()
		self.assertTrue(after_time >= before_time + 10)
		self.assertNotEqual(window, None)
		self.assertTrue(isinstance(window, ApplicationTestWindow))
Esempio n. 37
0
    def run( self ) :
        frame = JFrame(
           'CardLayout',
            layout = BorderLayout(),
            defaultCloseOperation = JFrame.EXIT_ON_CLOSE
        )

        cp = frame.getContentPane()
        self.addButtons( cp, BorderLayout.NORTH )
        self.addCards( cp, BorderLayout.CENTER )

        frame.setSize( 300, 125 )
        frame.setVisible( 1 )
Esempio n. 38
0
class ActionMenu:
    def __init__(self):
        self.titleBase = 'HCR2 Monkey'
        self.frame = JFrame(self.titleBase,
                            defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
                            size=(300, 250))
        self.inputMap = self.frame.getRootPane().getInputMap(
            JComponent.WHEN_IN_FOCUSED_WINDOW)
        self.actionMap = self.frame.getRootPane().getActionMap()
        self.actionLabels = {}
        self.actionThread = None

        self.defaultBackground = self.frame.getBackground()
        self.frame.getContentPane().setLayout(
            BoxLayout(self.frame.getContentPane(), BoxLayout.Y_AXIS))

        self.addAction("ESCAPE", "Abort current action", lambda: None)

    def addAction(self, key, desc, cb):
        if " " in key:
            strokeString = key
        else:
            strokeString = "pressed " + key

        stroke = KeyStroke.getKeyStroke(strokeString)
        if stroke == None:
            raise ValueError("Invalid key: " + str(key))
        self.inputMap.put(stroke, key)
        self.actionMap.put(key, MenuAction(cb, key, desc, self))
        self.actionLabels[key] = JLabel(key + ": " + desc)
        self.actionLabels[key].setOpaque(True)
        self.frame.getContentPane().add(self.actionLabels[key])

    def run(self):
        log("Starting menu")
        self.frame.visible = True
        while True:
            sleep(300)
Esempio n. 39
0
class ActionMenu:
    def __init__(self):
        self.titleBase = 'FF3 Monkey'
        self.frame = JFrame(self.titleBase, defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size=(400,400))
        self.inputMap = self.frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
        self.actionMap = self.frame.getRootPane().getActionMap()
        self.actionLabels = {}
        self.actionThread = None

        self.defaultBackground = self.frame.getBackground()
        self.frame.getContentPane().setLayout(BoxLayout(self.frame.getContentPane(), BoxLayout.Y_AXIS))

        def quit():
            from java.lang import System
            print "Quitting..."
            System.exit(0)
        self.addAction("Q", "Quit", quit)
        self.addAction("ESCAPE", "Abort current action", lambda: None)
    def addAction(self, key, desc, cb):
        if " " in key:
            strokeString = key
        else:
            strokeString = "pressed "+key

        stroke = KeyStroke.getKeyStroke(strokeString)
        if stroke == None:
            raise ValueError("Invalid key: "+str(key))
        self.inputMap.put(stroke, key)
        self.actionMap.put(key, MenuAction(cb, key, desc, self))
        self.actionLabels[key] = JLabel(key+": "+desc)
        self.actionLabels[key].setOpaque(True)
        self.frame.getContentPane().add(self.actionLabels[key])
    def run(self):
        print "Starting menu"
        self.frame.visible = True
        while True:
            sleep(300)
Esempio n. 40
0
class ContactsListGUI(ContactsList):
    """A GUI object that displays a contacts list"""
    def __init__(self, chatui):
        ContactsList.__init__(self, chatui)
        self.clientsByName = {}
        self.mainframe = JFrame("Contacts List")
        self.headers = ["Contact", "Status", "Idle", "Account"]
        self.data = UneditableTableModel([], self.headers)
        self.table = JTable(self.data,
                            columnSelectionAllowed = 0, #cannot select columns
                            selectionMode = ListSelectionModel.SINGLE_SELECTION)

        self.buildpane()
        self.mainframe.pack()
        self.mainframe.show()

    def setContactStatus(self, person):
        ContactsList.setContactStatus(self, person)
        self.update()

    def registerAccountClient(self, client):
        ContactsList.registerAccountClient(self, client)
        if not client.accountName in self.clientsByName.keys():
            self.clientsByName[client.accountName] = client

    def unregisterAccount(self, client):
        ContactsList.unregisterAccountClient(self, client)
        if client.accountName in self.clientsByName.keys():
            del self.clientsByName[client.accountName]

    def contactChangedNick(self, person, newnick):
        ContactsList.contactChangedNick(self, person, newnick)
        self.update()

    #GUI code
    def buildpane(self):
        buttons = JPanel(FlowLayout(), doublebuffered)
        buttons.add(JButton("Send Message", actionPerformed=self.message))
        buttons.add(JButton("Add Contact", actionPerformed=self.addContact))
        #buttons.add(JButton("Quit", actionPerformed=self.quit))

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.Y_AXIS))
        mainpane.add(JScrollPane(self.table))
        mainpane.add(buttons)
        self.update()

    def update(self):
        contactdata = []
        for contact in self.onlineContacts.values():
            if contact.status == AWAY:
                stat = "(away)"
            else:
                stat = "(active)"
            contactdata.append([contact.name, stat, contact.getIdleTime(),
                                contact.client.accountName])
        self.data.setDataVector(contactdata, self.headers)

    #callable actionlisteners
    def message(self, ae):
        row = self.table.getSelectedRow()
        if row < 0:
            print "Trying to send IM to person, but no person selected"
        else:
            person = self.onlineContacts[self.data.getValueAt(row, 0)]
            self.chat.getConversation(person)

    def addContact(self, ae):
        _AccountAdder(self)

    def quit(self, ae):
        sys.exit()
Esempio n. 41
0
class NewAccountGUI:
    def __init__(self, amgui):
        self.amgui = amgui
        self.am = amgui.acctmanager
        self.buildgwinfo()
        self.autologin = JCheckBox("Automatically Log In")
        self.acctname = JTextField()
        self.gwoptions = JPanel(doublebuffered)
        self.gwoptions.border = TitledBorder("Gateway Options")
        self.buildgwoptions("Twisted")
        self.mainframe = JFrame("New Account Window")
        self.buildpane()

    def buildgwinfo(self):
        self.gateways = {
            "Twisted": {
                "ident": JTextField(),
                "passwd": JPasswordField(),
                "host": JTextField("twistedmatrix.com"),
                "port": JTextField("8787"),
                "service": JTextField("twisted.words"),
                "persp": JTextField(),
            },
            "AIM": {
                "ident": JTextField(),
                "passwd": JPasswordField(),
                "host": JTextField("toc.oscar.aol.com"),
                "port": JTextField("9898"),
            },
            "IRC": {
                "ident": JTextField(),
                "passwd": JPasswordField(),
                "host": JTextField(),
                "port": JTextField("6667"),
                "channels": JTextField(),
            },
        }
        self.displayorder = {
            "Twisted": [
                ["Identity Name", "ident"],
                ["Password", "passwd"],
                ["Host", "host"],
                ["Port", "port"],
                ["Service Name", "service"],
                ["Perspective Name", "persp"],
            ],
            "AIM": [["Screen Name", "ident"], ["Password", "passwd"], ["Host", "host"], ["Port", "port"]],
            "IRC": [
                ["Nickname", "ident"],
                ["Password", "passwd"],
                ["Host", "host"],
                ["Port", "port"],
                ["Channels", "channels"],
            ],
        }

    def buildgwoptions(self, gw):
        self.gwoptions.removeAll()
        self.gwoptions.layout = GridLayout(len(self.gateways[gw]), 2)
        for mapping in self.displayorder[gw]:
            self.gwoptions.add(JLabel(mapping[0]))
            self.gwoptions.add(self.gateways[gw][mapping[1]])

    def buildpane(self):
        gw = JPanel(GridLayout(1, 2), doublebuffered)
        gw.add(JLabel("Gateway"))
        self.gwlist = JComboBox(self.gateways.keys())  # , actionPerformed=self.changegw)
        self.gwlist.setSelectedItem("Twisted")
        gw.add(self.gwlist)

        stdoptions = JPanel(GridLayout(2, 2), doublebuffered)
        stdoptions.border = TitledBorder("Standard Options")
        stdoptions.add(JLabel())
        stdoptions.add(self.autologin)
        stdoptions.add(JLabel("Account Name"))
        stdoptions.add(self.acctname)

        buttons = JPanel(FlowLayout(), doublebuffered)
        buttons.add(JButton("OK", actionPerformed=self.addaccount))
        buttons.add(JButton("Cancel", actionPerformed=self.cancel))

        mainpane = self.mainframe.getContentPane()
        mainpane.layout = BoxLayout(mainpane, BoxLayout.Y_AXIS)
        mainpane.add(gw)
        mainpane.add(self.gwoptions)
        mainpane.add(stdoptions)
        mainpane.add(buttons)

    def show(self):
        self.mainframe.setLocation(100, 100)
        self.mainframe.pack()
        self.mainframe.show()

    # actionlisteners
    def changegw(self, ae):
        self.buildgwoptions(self.gwlist.getSelectedItem())
        self.mainframe.pack()
        self.mainframe.show()

    def addaccount(self, ae):
        gwselection = self.gwlist.getSelectedItem()
        gw = self.gateways[gwselection]
        name = gw["ident"].text
        passwd = gw["passwd"].text
        host = gw["host"].text
        port = int(gw["port"].text)
        autologin = self.autologin.isSelected()
        acctname = self.acctname.text

        if gwselection == "Twisted":
            sname = gw["service"].text
            perspective = gw["persp"].text
            self.am.addAccount(PBAccount(acctname, autologin, name, passwd, host, port, [[stype, sname, perspective]]))
        elif gwselection == "AIM":
            self.am.addAccount(TOCAccount(acctname, autologin, name, passwd, host, port))
        elif gwselection == "IRC":
            channels = gw["channels"].text
            self.am.addAccount(IRCAccount(acctname, autologin, name, passwd, host, port, channels))

        self.amgui.update()
        print "Added new account"
        self.mainframe.dispose()

    def cancel(self, ae):
        print "Cancelling new account creation"
        self.mainframe.dispose()
Esempio n. 42
0
size = Dimension(600, 200 * numberOfStringPairs)

panel.setSize(size)
panel.setPreferredSize(size)

records.sort()
for record in records:
    try:
        oldname, oldVertices, oldEdges = record.oldstring.split(' ')
        newname, newVertices, newEdges = record.newstring.split(' ')

        oldPanel = LinearViewPanel(300, 200)
        oldPanel.renderVertices(oldVertices)
        oldPanel.renderEdges(oldEdges)
        oldPanel.setToolTipText(oldname)
        panel.add(oldPanel)

        newPanel = LinearViewPanel(300, 200)
        newPanel.renderVertices(newVertices)
        newPanel.renderEdges(newEdges)
        newPanel.setToolTipText(newname)
        panel.add(newPanel)
    except ValueError:
        pass
        #print oldstring, newstring

scrollPane = JScrollPane(panel, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED)
scrollPane.setSize(800,400)
frame.getContentPane().add(scrollPane)
frame.setVisible(1)
Esempio n. 43
0
button = JButton("selected?", actionPerformed=click)
addButton = JButton("add 7", actionPerformed=add)
remButton = JButton("remove element", actionPerformed=rem)
chButton = JButton("Change to list B", actionPerformed=change)



listModel = DefaultListModel()
[listModel.addElement(e) for e in liste]
li = JList(listModel)
spane = JScrollPane(li) # making the list scrollable. li is now inside container JScrollPane


#b = JButton("press", actionPerformed=rem)
p.add(spane)
p.add(button)
p.add(addButton)
p.add(remButton)
p.add(chButton)
f.add(p)
f.pack()
f.setLocationRelativeTo(None)
f.setVisible(True)

print f.getParent()
print f.getLocationOnScreen()
print f.getContentPane().getSize()


Esempio n. 44
0
class Window:
    def __init__(self, text):
        self.frame = JFrame()
        self.frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
        self.frame.getContentPane().setLayout(GridLayout(1, 1))
        self.settings = Settings()
        self.text = text
        self + text
        m = JMenuBar()
        self.menubar = m
        self.filemenu = self.menu()
        m.add(self.filemenu)
        self.frame.setJMenuBar(self.menubar)
        self.frame.setSize(1000, 600)
        self.frame.setVisible(1)

    def menu(self):
        f = JMenu("File")

        o = JMenuItem("Copy")
        o.addActionListener(ActionEventListener(self.opencopy))
        self.open = o
        f.add(o)

        o = JMenuItem("New")
        o.addActionListener(ActionEventListener(self.new))
        self.open = o
        f.add(o)

        o = JMenuItem("Open")
        o.addActionListener(ActionEventListener(self.opendialog))
        self.open = o
        f.add(o)

        o = JMenuItem("Save")
        o.addActionListener(ActionEventListener(self.save))
        self.open = o
        f.add(o)

        o = JMenuItem("Save As")
        o.addActionListener(ActionEventListener(self.saveas))
        self.open = o
        f.add(o)

        return f

    def __add__(self, c):
        self.frame.getContentPane().add(c)
        return self

    def opencopy(self, e):
        c = None
        if "lastcopy" in self.settings.keys():
            c = JFileChooser(self.settings["lastcopy"])
        else:
            c = JFileChooser()

        r = c.showOpenDialog(self.frame)

        if r == JFileChooser.APPROVE_OPTION:
            f = c.getSelectedFile()
            self.f = f
            s = f.getAbsolutePath()

            self.settings["lastcopy"] = f.getParent()
            self.settings.save()

            #            i = FileInputStream(s)
            self.text.setcopy(s)

    def opendialog(self, e):
        c = None
        if "lastdir" in self.settings.keys():
            c = JFileChooser(self.settings["lastdir"])
        else:
            c = JFileChooser()

        r = c.showOpenDialog(self.frame)

        if r == JFileChooser.APPROVE_OPTION:
            f = c.getSelectedFile()
            self.f = f
            s = f.getAbsolutePath()

            self.settings["lastdir"] = f.getParent()
            self.settings.save()

            i = FileInputStream(s)
            self.text.setinput(i)
            self.frame.pack()
            self.frame.setSize(800, 500)

    def new(self, e):
        self.text.createnew()
        self.frame.pack()
        self.frame.setSize(800, 500)

    def save(self, e):
        o = FileOutputStream(self.f)
        self.text.setoutput(o)

    def saveas(self, e):
        c = None
        if "lastdir" in self.settings.keys():
            c = JFileChooser(self.settings["lastdir"])
        else:
            c = JFileChooser()

        r = c.showOpenDialog(self.frame)

        if r == JFileChooser.APPROVE_OPTION:
            f = c.getSelectedFile()
            self.f = f
            s = f.getAbsolutePath()

            self.settings["lastdir"] = f.getParent()
            self.settings.save()

            o = FileOutputStream(s)
            self.text.setoutput(o)
Esempio n. 45
0
main_panel = JPanel()

### panel 1
panel1 = JPanel()
panel1.add(lbl1)
cb1 = JComboBox(choice_list)
btn1 = JButton("Accept")
btn1.addActionListener(ButtonListener(btn1))
panel1.add(cb1)
panel1.add(btn1)

### panel 2
panel2 = JPanel()
panel2.add(lbl2)
cb2 = JComboBox(sorted(roi_ni.keys()))
cb2.addActionListener(Listener(lbl2, cb2))
panel2.add(cb2)

### panel 3
pnl3 = JPanel()
lst1 = JList(listmodel)
pnl3.add(lst1)

frame = JFrame("Swing GUI Test Frame")
frame.getContentPane().add(main_panel)
main_panel.add(panel1)
main_panel.add(panel2)
main_panel.add(pnl3)
frame.pack()
frame.setVisible(True)
Esempio n. 46
0
    formColors[i].add("Yellow")
    formColors[i].add("White")
    formColors[i].select(i)
    inputPanel.add(formColors[i])

    inputPanel.add(JLabel("  Type"))
    formType.append(Choice())
    formType[i].add("Image channel")
    formType[i].add("XY View")
    formType[i].add("XZ View")
    formType[i].add("ZY View")
    inputPanel.add(formType[i])

controlPanel = JPanel()
controlPanel.setLayout(GridLayout(1, 3))
stopBtn = JButton("Cancel")
stopBtn.addActionListener(CancelHandler(job, frame))
controlPanel.add(stopBtn)
yamlBtn = JButton("Generate YAML only")
yamlBtn.addActionListener(StartHandler(job, frame, True))
controlPanel.add(yamlBtn)
startBtn = JButton("Generate HDF5+YAML")
startBtn.addActionListener(StartHandler(job, frame, False))
controlPanel.add(startBtn)

frame.getContentPane().add(infoPanel, BorderLayout.NORTH)
frame.getContentPane().add(JScrollPane(inputPanel), BorderLayout.CENTER)
frame.getContentPane().add(controlPanel, BorderLayout.SOUTH)
frame.pack()
frame.setVisible(True)
def doall(locations, fileobs,filerun1,filerun2,stime,etime,imageDir='d:/temp',weights=None,filter_type="AVE",normalize=False):
    obs=HecDss.open(fileobs,True)
    obs.setTimeWindow(stime,etime)
    run1=HecDss.open(filerun1,True)
    run1.setTimeWindow(stime,etime)
    if filerun2 != None:
        run2=HecDss.open(filerun2,True)
        run2.setTimeWindow(stime,etime)
    else:
        run2=None
    rms1=0
    rms1_min,rms1_max=0,0
    rms2=0
    rms2_min,rms2_max=0,0
    rmsmap={}
    #run2=None
    sumwts=0
    average_interval=None;
    for l in locations:
        data1=get_matching(obs,'A=%s C=%s E=15MIN'%(l,type))
        if data1 == None:
            data1=get_matching(obs,'A=%s C=%s E=1DAY'%(l,type))
        if data1 == None:
            data1=get_matching(obs,'A=%s C=%s E=IR-DAY'%(l,type))
        if data1 == None:
            data1=get_matching(obs,'A=%s C=%s E=1HOUR'%(l,type))
        drun1=get_matching(run1,'B=%s C=%s'%(l,type))
        if run2 != None:
            drun2=get_matching(run2, 'B=%s C=%s'%(l,type))
        else:
            drun2=None
        avg_intvl="1DAY"
        if data1 != None:
            if average_interval != None:
                dobsd=TimeSeriesMath(data1).transformTimeSeries(average_interval, None, filter_type, 0)
            else:
                dobsd=TimeSeriesMath(data1)
            if normalize:
                dobsd=dobsd.divide(TimeSeriesMath(data1).mean())
            dobsm=TimeSeriesMath(data1).transformTimeSeries(avg_intvl, None, filter_type, 0)
            dobsm_max=TimeSeriesMath(data1).transformTimeSeries(avg_intvl, None, "MAX", 0)
            dobsm_max.data.fullName=dobsm_max.data.fullName+"MAX"
            dobsm_min=TimeSeriesMath(data1).transformTimeSeries(avg_intvl, None, "MIN", 0)
            dobsm_min.data.fullName=dobsm_min.data.fullName+"MIN"
            if normalize:
                dobsm=dobsm.divide(TimeSeriesMath(data1).mean())
        if drun1==None:
            continue;
        else:
            if average_interval != None:
                drun1d=TimeSeriesMath(drun1).transformTimeSeries(average_interval, None, filter_type, 0)
            else:
                drun1d=TimeSeriesMath(drun1)
            if normalize:
                drun1d=drun1d.divide(TimeSeriesMath(drun1).mean())
            if drun2 != None:
                if average_interval != None:
                    drun2d=TimeSeriesMath(drun2).transformTimeSeries(average_interval, None, filter_type, 0)
                else:
                    drun2d=TimeSeriesMath(drun2)
                if normalize:
                    drun2d=drun2d.divide(TimeSeriesMath(drun2).mean())
            drun1m=TimeSeriesMath(drun1).transformTimeSeries(avg_intvl, None, filter_type, 0)
            drun1m_max=TimeSeriesMath(drun1).transformTimeSeries(avg_intvl, None, "MAX", 0)
            drun1m_min=TimeSeriesMath(drun1).transformTimeSeries(avg_intvl, None, "MIN", 0)
            if normalize:
                drun1m=drun1m.divide(TimeSeriesMath(drun1).mean())
            if drun2 != None:
                drun2m=TimeSeriesMath(drun2).transformTimeSeries(avg_intvl, None, filter_type, 0)
                drun2m_max=TimeSeriesMath(drun2).transformTimeSeries(avg_intvl, None, "MAX", 0)
                drun2m_min=TimeSeriesMath(drun2).transformTimeSeries(avg_intvl, None, "MIN", 0)
                if normalize:
                    drun2m=drun2m.divide(TimeSeriesMath(drun2).mean())
            else:
                drun2m=None
        if weights != None:
            sumwts=sumwts+weights[l]
            lrms1 = calculate_rms(drun1m.data, dobsm.data)*weights[l]
            lrms1_min=calculate_rms(drun1m_min.data,dobsm_min.data)*weights[l]
            lrms1_max=calculate_rms(drun1m_max.data,dobsm_max.data)*weights[l]
            rms1=rms1+lrms1
            rms1_min=rms1_min+lrms1_min
            rms1_max=rms1_max+lrms1_max
            lrms2 = calculate_rms(drun2m.data,dobsm.data)*weights[l]
            lrms2_min=calculate_rms(drun2m_min.data,dobsm_min.data)*weights[l]
            lrms2_max=calculate_rms(drun2m_max.data,dobsm_max.data)*weights[l]
            rmsmap[l] = lrms1,lrms2,lrms1_min,lrms2_min,lrms1_max,lrms2_max
            rms2=rms2+lrms2
            rms2_min=rms2_min+lrms2_min
            rms2_max=rms2_max+lrms2_max
        plotd = newPlot("Hist vs New Geom [%s]"%l)
        if data1 != None:
            plotd.addData(dobsd.data)
        plotd.addData(drun1d.data)
        if drun2 != None:
            plotd.addData(drun2d.data)
        plotd.showPlot()
        legend_label = plotd.getLegendLabel(drun1d.data)
        legend_label.setText(legend_label.getText()+" ["+str(int(lrms1*100)/100.)+","+str(int(lrms1_min*100)/100.)+","+str(int(lrms1_max*100)/100.)+"]")
        legend_label = plotd.getLegendLabel(drun2d.data)
        legend_label.setText(legend_label.getText()+" ["+str(int(lrms2*100)/100.)+","+str(int(lrms2_min*100)/100.)+","+str(int(lrms2_max*100)/100.)+"]")
        plotd.setVisible(False)
        xaxis=plotd.getViewport(0).getAxis("x1")
        vmin =xaxis.getViewMin()+261500. # hardwired to around july 1, 2008
        xaxis.setViewLimits(vmin,vmin+10000.)
        if data1 != None:
            pline = plotd.getCurve(dobsd.data)
            pline.setLineVisible(1)
            pline.setLineColor("blue")
            pline.setSymbolType(Symbol.SYMBOL_CIRCLE)
            pline.setSymbolsVisible(0)
            pline.setSymbolSize(3)
            pline.setSymbolSkipCount(0)
            pline.setSymbolFillColor(pline.getLineColorString())
            pline.setSymbolLineColor(pline.getLineColorString())
            g2dPanel = plotd.getPlotpanel()
            g2dPanel.revalidate();
            g2dPanel.paintGfx();
        plotm = newPlot("Hist vs New Geom Monthly [%s]"%l)
        plotm.setSize(1800,1200)
        if data1 != None:
            plotm.addData(dobsm.data)
           #plotm.addData(dobsm_max.data)
            #plotm.addData(dobsm_min.data)
        plotm.addData(drun1m.data)
        #plotm.addData(drun1m_max.data)
        #plotm.addData(drun1m_min.data)
        if drun2 != None:
            plotm.addData(drun2m.data)
            #plotm.addData(drun2m_max.data)
            #plotm.addData(drun2m_min.data)
        plotm.showPlot()
        if data1 != None:
            pline = plotm.getCurve(dobsm.data)
            pline.setLineVisible(1)
            pline.setLineColor("blue")
            pline.setSymbolType(Symbol.SYMBOL_CIRCLE)
            pline.setSymbolsVisible(0)
            pline.setSymbolSize(3)
            pline.setSymbolSkipCount(0)
            pline.setSymbolFillColor(pline.getLineColorString())
            pline.setSymbolLineColor(pline.getLineColorString())
        plotm.setVisible(False)
        if data1 != None:
            plots=do_regression_plots(dobsm,drun1m,drun2m)
            if plots != None:
                spanel = plots.getPlotpanel()
                removeToolbar(spanel)
        mpanel = plotm.getPlotpanel()
        removeToolbar(mpanel)
        dpanel = plotd.getPlotpanel()
        removeToolbar(dpanel)
        from javax.swing import JPanel,JFrame
        from java.awt import GridBagLayout, GridBagConstraints
        mainPanel = JPanel()
        mainPanel.setLayout(GridBagLayout())
        c=GridBagConstraints()
        c.fill=c.BOTH
        c.weightx,c.weighty=0.5,1
        c.gridx,c.gridy,c.gridwidth,c.gridheight=0,0,10,4
        if data1 != None:
            if plots != None:
                pass
                #mainPanel.add(spanel,c)
        c.gridx,c.gridy,c.gridwidth,c.gridheight=0,0,10,4
        c.weightx,c.weighty=1,1
        mainPanel.add(mpanel,c)
        c.gridx,c.gridy,c.gridwidth,c.gridheight=0,4,10,6
        mainPanel.add(dpanel,c)
        fr=JFrame()
        fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
        fr.getContentPane().add(mainPanel)
        fr.setSize(1100,850);
        fr.show();
        mainPanel.setSize(1100,850);
        mainPanel.setBackground(Color.WHITE);
        #import time; time.sleep(5)
        saveToPNG(mainPanel,imageDir+l+".png")
    if weights != None:
        rms1=(rms1+rms1_min+rms1_max)/sumwts
        rms2=(rms2+rms2_min+rms2_max)/sumwts
        print 'RMS Run 1: %f'%rms1
        print 'RMS Run 2: %f'%rms2
        for loc in rmsmap.keys():
            print loc, rmsmap[loc] 
Esempio n. 48
0
def makeEditorFrame(ldPath, compiler):
    mb = JMenuBar()
    
    file = JMenu("File")
    edit = JMenu("Edit")
    run = JMenu("Run")
    
    newMenu = menu_with_accelerator("New",(KeyEvent.VK_N,ActionEvent.META_MASK))
    file.add(newMenu)
           
    open = menu_with_accelerator("Open",(KeyEvent.VK_O,ActionEvent.META_MASK))
    file.add(open)
    
    save = menu_with_accelerator("Save",(KeyEvent.VK_S,ActionEvent.META_MASK))
    file.add(save)
    
    file.add(JSeparator());
    
    resetPipe = menu_with_accelerator("Reset Pipeline",(KeyEvent.VK_N,ActionEvent.META_MASK | ActionEvent.SHIFT_MASK))
    file.add(resetPipe)
            
    openPipe = menu_with_accelerator("Open Pipeline",(KeyEvent.VK_O,ActionEvent.META_MASK | ActionEvent.SHIFT_MASK))
    file.add(openPipe)
            
    compile = menu_with_accelerator("Compile",(KeyEvent.VK_ENTER, ActionEvent.META_MASK))
    run.add(compile)
            
    mb.add(file)
    mb.add(edit)
    mb.add(run)
            
    f = JFrame("SFGP Shader Editor")
    f.setJMenuBar(mb)
    c = f.getContentPane()
    c.setLayout(BorderLayout())
    editor = GLSLEditorPane("",ldPath,compiler)
    c.add(editor, BorderLayout.CENTER)
    c.doLayout()
    
    f.setSize(1000, 700);
    f.setVisible(True);
    f.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            
    class EditorActionListener(ActionListener):
        def makeRelay(srcObj):
            return (lambda e: editor.actionPerformed(ActionEvent(srcObj, e.getID(), e.getActionCommand())))
        editorActions = {
            save : (lambda e: editor.saveCurrent()),
            compile : (lambda e: editor.compileCurrent()),
            open : makeRelay(editor.openShader),
            newMenu : makeRelay(editor.newShader),
            openPipe : makeRelay(editor.openPipeline),
            resetPipe : makeRelay(editor.resetPipeline)
                        }
        def actionPerformed(self, e):
            editorActions = EditorActionListener.editorActions
            evtSrc = e.getSource()
            if evtSrc in editorActions:
                editorActions[evtSrc](e)
            else:
                raise IllegalStateException("Imaginary menu item registered an ActionEvent: " + evtSrc)
    menuListener = EditorActionListener()
    compile.addActionListener(menuListener);
    newMenu.addActionListener(menuListener);
    open.addActionListener(menuListener);
    save.addActionListener(menuListener);
    resetPipe.addActionListener(menuListener);
    openPipe.addActionListener(menuListener);
class StackOverlay:
    def __init__(self):
        self.frame = None
        self.overlayColorPreviewLabel = None
        self.showStackOverlayWindow()
        self.overlayColor = None

    def onQuit(self, e):
        print "Exiting..."
        self.frame.dispose()
        
    def showColorChooser(self, e):
        colorChooser = JColorChooser()
        self.overlayColor = colorChooser.showDialog(self.frame, "Choose color", Color.red)
        self.overlayColorPreviewLabel.setBackground(self.overlayColor)

    def showStackOverlayWindow(self):
        all = JPanel()
        all.setLayout(MigLayout())

        self.imageIDs = WindowManager.getIDList()
        self.imageNames = []

        if self.imageIDs is None:
            IJ.error("No open images", "Stack Overlay requires at least one image to be already open.")
            return

        for i in self.imageIDs:
            self.imageNames.append(WindowManager.getImage(i).getTitle())

        self.baseImageBox = JComboBox(self.imageNames)
        baseImageBoxLabel = JLabel("Base image")
        self.baseImageBox.setSelectedIndex(0)
        all.add(baseImageBoxLabel)
        all.add(self.baseImageBox, "wrap")

        self.overlayImageBox = JComboBox(self.imageNames)
        overlayImageBoxLabel = JLabel("Overlay image")
        if len(self.imageNames) > 1:
            self.overlayImageBox.setSelectedIndex(1)

        all.add(overlayImageBoxLabel)
        all.add(self.overlayImageBox, "wrap")

        all.add(JSeparator(SwingConstants.HORIZONTAL), "span, wrap")

        overlayStyleFrame = JPanel()
        overlayStyleFrame.setLayout(MigLayout())
        overlayStyleFrame.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Overlay Style"), BorderFactory.createEmptyBorder(5,5,5,5)))

        colorLabel = JLabel("Overlay color")
        self.overlayColorPreviewLabel = JLabel("           ")
        self.overlayColorPreviewLabel.setBorder(BorderFactory.createEmptyBorder(0,0,1,0))
        self.overlayColorPreviewLabel.setOpaque(True)
        self.overlayColorPreviewLabel.setBackground(Color.red)
        self.overlayColor = Color.red
        colorPicker = JColorChooser()
        colorPicker.setPreviewPanel(self.overlayColorPreviewLabel)
        colorButton = JButton("Select color...", actionPerformed=self.showColorChooser)

        opacityLabel = JLabel("Overlay opacity (%)")
        opacitySpinnerModel = SpinnerNumberModel(100, 0, 100, 1)
        self.opacitySpinner = JSpinner(opacitySpinnerModel)

        overlayStyleFrame.add(colorLabel)
        overlayStyleFrame.add(self.overlayColorPreviewLabel)
        overlayStyleFrame.add(colorButton, "wrap")

        overlayStyleFrame.add(opacityLabel)
        overlayStyleFrame.add(self.opacitySpinner, "wrap")
        

        all.add(overlayStyleFrame, "span, wrap")
        
        self.virtualStackCheckbox = JCheckBox("Use Virtual Stack", True)
        all.add(self.virtualStackCheckbox, "span, wrap")

        # TODO: add non-thermonuclear cancel button functionality
        overlayCancelButton = JButton("Cancel", actionPerformed=self.onQuit)
        overlayStartButton = JButton("Overlay images", actionPerformed=self.overlayImages)
        
        all.add(overlayCancelButton, "gapleft push")
        all.add(overlayStartButton, "gapleft push")

        self.frame = JFrame("Stack Overlay")
        self.frame.getContentPane().add(JScrollPane(all))
        self.frame.pack()
        self.frame.setLocationRelativeTo(None)
        self.frame.setVisible(True)
        
    def overlayImages(self, e):
        impBase = WindowManager.getImage(self.imageIDs[self.baseImageBox.getSelectedIndex()])
        refBase = impBase.getStack().getProcessor(1)
        
        impOverlay = WindowManager.getImage(self.imageIDs[self.overlayImageBox.getSelectedIndex()])
        refOverlay = impOverlay.getStack().getProcessor(1)
        
        print "Overlaying for stack sizes " + str(impBase.getStackSize()) + "/" + str(impOverlay.getStackSize()) + "..."
        
        stack = None
        
        if self.virtualStackCheckbox.isSelected():
            stack = OverlayVirtualStack()
            stack.overlayOpacity = float(self.opacitySpinner.getValue())/100.0
            stack.overlayColor = AWTColorToArray(self.overlayColorPreviewLabel.getBackground())
            stack.base = impBase
            stack.overlay = impOverlay

            ImagePlus("Stack Overlay from " + self.imageNames[self.baseImageBox.getSelectedIndex()] + " and " + self.imageNames[self.overlayImageBox.getSelectedIndex()], stack).show()
        else:
            IJ.error("Not implemented yet", "Using normal stacks is not implemented yet. Please use the Virtual Stack option.")
    def __init__(self, imgData):
        n = imgData.size()
        win = JFrame("Point Marker Panel")
        win.setPreferredSize(Dimension(350, 590))
        win.setSize(win.getPreferredSize())
        pan = JPanel()
        pan.setLayout(BoxLayout(pan, BoxLayout.Y_AXIS))
        win.getContentPane().add(pan)

        progressPanel = JPanel()
        progressPanel.setLayout(BoxLayout(progressPanel, BoxLayout.Y_AXIS))
        positionBar = JProgressBar()
        positionBar.setMinimum(0)
        positionBar.setMaximum(n)
        positionBar.setStringPainted(True)
        progressPanel.add(Box.createGlue())
        progressPanel.add(positionBar)

        progressBar = JProgressBar()
        progressBar.setMinimum(0)
        progressBar.setMaximum(n)
        progressBar.setStringPainted(True)
        progressPanel.add(progressBar)
        progressPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(progressPanel)

        pan.add(Box.createRigidArea(Dimension(5,5)))
        savePanel = JPanel()
        savePanel.setLayout(BoxLayout(savePanel, BoxLayout.Y_AXIS))
        saveMessageLabel = JLabel("<html><u>Save Often</u></html>")
        savePanel.add(saveMessageLabel)
        savePanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        savePanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(savePanel)
        # pan.add(saveMessageLabel)

        pan.add(Box.createRigidArea(Dimension(5,5)))
        calPanel = JPanel()
        calPanel.setLayout(BoxLayout(calPanel, BoxLayout.Y_AXIS))
        calPanelIn = JPanel()
        calPanelIn.setLayout(BoxLayout(calPanelIn, BoxLayout.X_AXIS))
        pixelSizeText = JTextField(12)
        pixelSizeText.setHorizontalAlignment(JTextField.RIGHT)
        # pixelSizeText.setMaximumSize(pixelSizeText.getPreferredSize())
        unitText = JTextField(10)
        # unitText.setMaximumSize(unitText.getPreferredSize())
        pixelSizeText.setText("Enter Pixel Size Here")
        calPanelIn.add(pixelSizeText)
        unitText.setText("Unit")
        calPanelIn.add(unitText)
        calPanelIn.setAlignmentX(Component.CENTER_ALIGNMENT)
        calPanelIn.setBorder(BorderFactory.createTitledBorder("Custom Calibration"))
        calPanel.add(calPanelIn)
        calPanelIn.setAlignmentX(Component.CENTER_ALIGNMENT)
        calPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(calPanel)

        pan.add(Box.createRigidArea(Dimension(5,5)))
        helpPanel = JPanel()
        helpPanel.setLayout(BoxLayout(helpPanel, BoxLayout.Y_AXIS))
        helpLable = JLabel("<html><ul>\
                            <li>Focus on Image Window</li>\
                            <li>Select multi-point Tool</li>\
                            <li>Click to Draw Points</li>\
                            <li>Drag to Move Points</li>\
                            <li>\"Alt\" + Click to Erase Points</li>\
                            <li>Optional: Customize Calibration Above\
                                 and Refresh Images\
                                (won't be written to files)</li>\
                            </html>")
        helpLable.setBorder(BorderFactory.createTitledBorder("Usage"))
        keyTagOpen = "<span style=\"background-color: #FFFFFF\"><b><kbd>"
        keyTagClose = "</kbd></b></span>"
        keyLable = JLabel("<html><ul>\
                            <li>Next Image --- " + keyTagOpen + "&lt" + \
                                keyTagClose + "</li>\
                            <li>Previous Image --- " + keyTagOpen + ">" + \
                                keyTagClose + "</li>\
                            <li>Save --- " + keyTagOpen + "`" + keyTagClose + \
                                " (upper-left to TAB key)</li>\
                            <li>Next Unmarked Image --- " + keyTagOpen + \
                                "TAB" + keyTagClose + "</li></ul>\
                            </html>")
        keyLable.setBorder(BorderFactory.createTitledBorder("Keyboard Shortcuts"))
        helpPanel.add(helpLable)
        helpPanel.add(keyLable)
        helpPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        helpPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(helpPanel)

        # pan.add(Box.createRigidArea(Dimension(0, 10)))
        infoPanel = JPanel()
        infoPanel.setLayout(BoxLayout(infoPanel, BoxLayout.Y_AXIS))
        infoLabel = JLabel()
        infoLabel.setBorder(BorderFactory.createTitledBorder("Project Info"))
        infoPanel.add(infoLabel)
        infoPanel.setAlignmentX(Component.CENTER_ALIGNMENT)
        infoPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10))
        pan.add(infoPanel)

        win.setVisible(True)

        self.imgData = imgData
        self.win = win
        # self.progressPanel = progressPanel
        self.positionBar = positionBar
        self.progressBar = progressBar
        self.saveMessageLabel = saveMessageLabel
        self.infoLabel = infoLabel
        self.pixelSizeText = pixelSizeText
        self.unitText = unitText
        self.update()
Esempio n. 51
0
def run(scene, w=512, h=512, aa=1, threads=1):
    """Create GUI and perform ray-tracing."""
    # Make Swing not look like garbage (so much)
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
    # Setup frame
    frame = JFrame("RayTracer", defaultCloseOperation=JFrame.EXIT_ON_CLOSE, size=(w, h))
    frame.setIconImage(ImageIcon("resources/icon.png").getImage())
    canvas = RayTracePanel(w, h, aa, threads)
    frame.getContentPane().add(JScrollPane(canvas))

    # Save FileChooser
    fcS = JFileChooser()
    fcS.addChoosableFileFilter(FileNameExtensionFilter("Windows Bitmap (*.bmp)", ["bmp"]))
    fcS.addChoosableFileFilter(FileNameExtensionFilter("JPEG / JFIF (*.jpg)", ["jpg"]))
    fcS.addChoosableFileFilter(FileNameExtensionFilter("Portable Network Graphics (*.png)", ["png"]))

    def saveFile(event):
        """Performed when the save button is pressed"""
        result = fcS.showSaveDialog(frame)
        if result == JFileChooser.APPROVE_OPTION:
            file = fcS.getSelectedFile()
            fname = file.getPath()
            ext = fcS.getFileFilter().getExtensions()[0]
            if not fname.endswith("." + ext):
                file = File(fname + "." + ext)
            canvas.saveToFile(file, ext)

    # Open FileChooser
    fcO = JFileChooser()
    fcO.addChoosableFileFilter(FileNameExtensionFilter("RayTrace Scene File (*.rts)", ["rts"]))

    def openFile(event):
        """Performed when the open button is pressed"""
        result = fcO.showOpenDialog(frame)
        if result == JFileChooser.APPROVE_OPTION:
            fname = fcO.getSelectedFile().getPath()
            if fname.endswith(".rts"):
                f = open(fname, "rb")
                newScene = SceneFactory().buildScene(f)
                f.close()
                Painter(canvas, newScene, openButton, saveButton, stopButton).start()

    def exit(event):
        """Performed when the exit button is pressed"""
        import sys

        sys.exit(0)

    def stop(event):
        """Peformed when the stop button is pressed"""
        canvas.stopRendering()

    # Setup Menu
    menuBar = JMenuBar()
    menu = JMenu("File")
    menuBar.add(menu)
    openButton = JMenuItem("Open...", actionPerformed=openFile)
    openButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK))
    menu.add(openButton)
    saveButton = JMenuItem("Save as...", actionPerformed=saveFile)
    saveButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK))
    menu.add(saveButton)
    menu.addSeparator()
    stopButton = JMenuItem("Stop Render", actionPerformed=stop)
    stopButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0))
    stopButton.setEnabled(False)
    menu.add(stopButton)
    menu.addSeparator()
    closeButton = JMenuItem("Close", actionPerformed=exit)
    closeButton.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4, ActionEvent.ALT_MASK))
    menu.add(closeButton)
    frame.setJMenuBar(menuBar)

    # Finish initializing GUI
    self.pack()
Esempio n. 52
0
class AccountManagementGUI:
    def __init__(self):
        self.acctmanager = AccountManager()
        self.mainframe = JFrame("Account Manager")
        self.chatui = None
        self.headers = ["Account Name", "Status", "Autologin", "Gateway"]
        self.data = UneditableTableModel([], self.headers)
        self.table = JTable(self.data)
        self.table.columnSelectionAllowed = 0  # cannot select columns
        self.table.selectionMode = ListSelectionModel.SINGLE_SELECTION

        self.connectbutton = JButton("Connect", actionPerformed=self.connect)
        self.dconnbutton = JButton("Disconnect", actionPerformed=self.disconnect)
        self.deletebutton = JButton("Delete", actionPerformed=self.deleteAccount)
        self.buildpane()
        self.mainframe.pack()
        self.mainframe.show()

    def buildpane(self):
        buttons = JPanel(FlowLayout(), doublebuffered)
        buttons.add(self.connectbutton)
        buttons.add(self.dconnbutton)
        buttons.add(JButton("New", actionPerformed=self.addNewAccount))
        buttons.add(self.deletebutton)
        buttons.add(JButton("Quit", actionPerformed=self.quit))

        mainpane = self.mainframe.getContentPane()
        mainpane.layout = BoxLayout(mainpane, BoxLayout.Y_AXIS)
        mainpane.add(JScrollPane(self.table))
        mainpane.add(buttons)
        self.update()

    def update(self):
        self.data.setDataVector(self.acctmanager.getSnapShot(), self.headers)
        if self.acctmanager.isEmpty():
            self.deletebutton.setEnabled(0)
            self.connectbutton.setEnabled(0)
            self.dconnbutton.setEnabled(0)
        else:
            self.deletebutton.setEnabled(1)
            if not 1 in self.acctmanager.getConnectionInfo():  # all disconnected
                self.dconnbutton.setEnabled(0)
                self.connectbutton.setEnabled(1)
            elif not 0 in self.acctmanager.getConnectionInfo():  # all connected
                self.dconnbutton.setEnabled(1)
                self.connectbutton.setEnabled(0)
            else:
                self.dconnbutton.setEnabled(1)
                self.connectbutton.setEnabled(1)

    # callable button actions
    def connect(self, ae):
        print "Trying to connect"
        row = self.table.getSelectedRow()
        if row < 0:
            print "Trying to connect to an account but no account selected"
        else:
            acctname = self.data.getValueAt(row, 0)
            if not self.chatui:
                self.chatui = twisted.words.im.jychat.JyChatUI()
            self.acctmanager.connect(acctname, self.chatui)
            self.update()

    def disconnect(self, ae):
        print "Trying to disconnect"
        row = self.table.getSelectedRow()
        if row < 0:
            print "Trying to logoff an account but no account was selected."
        else:
            acctname = self.data.getValueAt(row, 0)
            self.acctmanager.disconnect(acctname)
            self.update()

    def addNewAccount(self, ae):
        print "Starting new account creation"
        NewAccountGUI(self).show()

    def deleteAccount(self, ae):
        print "Deleting account"
        row = self.table.getSelectedRow()
        if row < 0:
            print "Trying to delete an account but no account selected"
        else:
            acctname = self.data.getValueAt(row, 0)
            self.acctmanager.delAccount(acctname)
            self.update()

    def quit(self, ae):
        self.acctmanager.quit()
        sys.exit()
Esempio n. 53
0
d1 = ClientServer.getClientDisplay(client, 0)
d2 = ClientServer.getClientDisplay(client, 1)
refimg = client.getDataReference(0)
userline = client.getDataReference(1)

# get image in order to get its size and type schema
image = refimg.getData()
dom = getDomain(image)
LINES = dom.getY().getLength()
d = domainType(image)

# create line slider for client user
slide = VisADSlider("imgline",0,LINES,0,1.0,userline,d[1])

showAxesScales(d2,1)

# display everything...
frame = JFrame("Test T8 Client")
pane = frame.getContentPane()
pane.setLayout(BorderLayout())

# GridLayout with 1 row, 2 columns, 5 pixel horiz and vert gaps
panel = JPanel(GridLayout(1,2,5,5))
panel.add(d1.getComponent())
panel.add(d2.getComponent())
pane.add("Center",panel)
pane.add("North",slide)
frame.setSize(800,500)
frame.setVisible(1)

Esempio n. 54
0
class GroupConversationWindow(GroupConversation):
    """A GUI window of a conversation witha  group of people"""
    def __init__(self, group, chatui):
        GroupConversation.__init__(self, group, chatui)
        self.mainframe = JFrame(self.group.name)
        self.headers = ["Member"]
        self.memberdata = UneditableTableModel([], self.headers)
        self.display = JTextArea(columns=100, rows=15, editable=0, lineWrap=1)
        self.typepad = JTextField()
        self.buildpane()
        self.lentext = 0

    def show(self):
        self.mainframe.pack()
        self.mainframe.show()

    def hide(self):
        self.mainframe.hide()

    def showGroupMessage(self, sender, text, metadata=None):
        self.displayText(sender + ": " + text)

    def setGroupMembers(self, members):
        GroupConversation.setGroupMembers(self, members)
        self.updatelist()

    def setTopic(self, topic, author):
        topictext = "Topic: " + topic + ", set by " + author
        self.mainframe.setTitle(self.group.name + ": " + topictext)
        self.displayText(topictext)

    def memberJoined(self, member):
        GroupConversation.memberJoined(self, member)
        self.updatelist()

    def memberChangedNick(self, oldnick, newnick):
        GroupConversation.memberChangedNick(self, oldnick, newnick)
        self.updatelist()

    def memberLeft(self, member):
        GroupConversation.memberLeft(self, member)
        self.updatelist()

    #GUI code
    def buildpane(self):
        buttons = JPanel(doublebuffered)
        buttons.add(JButton("Hide", actionPerformed=self.hidewindow))

        memberpane = JTable(self.memberdata)
        memberframe = JScrollPane(memberpane)

        chat = JPanel(doublebuffered)
        chat.setLayout(BoxLayout(chat, BoxLayout.Y_AXIS))
        chat.add(JScrollPane(self.display))
        self.typepad.actionPerformed = self.send
        chat.add(self.typepad)
        chat.add(buttons)

        mainpane = self.mainframe.getContentPane()
        mainpane.setLayout(BoxLayout(mainpane, BoxLayout.X_AXIS))
        mainpane.add(chat)
        mainpane.add(memberframe)

    def displayText(self, text):
        self.lentext = self.lentext + len(text)
        self.display.append(text)
        self.display.setCaretPosition(self.lentext)

    def updatelist(self):
        self.memberdata.setDataVector([self.members], self.headers)

    #actionListener
    def send(self, ae):
        text = self.typepad.getText()
        self.typepad.setText("")
        if text != "" and text != None:
            GroupConversation.sendText(self, text)

    def hidewindow(self, ae):
        self.hide()
Esempio n. 55
0
class FcsImageShow(object):
	fcsimages = []
	idximg = -1
	def __init__(self):
		self.frameMain = JFrame('Open next image',
			defaultCloseOperation = JFrame.DISPOSE_ON_CLOSE,
			size = (300, 300)
		)
		pane = self.frameMain.getContentPane()
		panel = JPanel()
		panel.setLayout(BoxLayout(panel, BoxLayout.LINE_AXIS))
		panel.add(JButton('Next', actionPerformed=self.next))
		panel.add(JButton('Previous', actionPerformed=self.prev))
		pane.add(panel)
		self.frameMain.visible = 1
		
		#resfile = 'X:\\AntonioP_t2\\RLadurner_JMPeters\\DoubleArrest_Noc\\150130_STAG2\\two-comp-fit.res'
		
		#resfile = 'X:\\AntonioP_t2\\RLadurner_JMPeters\\DoubleArrest\\150120_STAG2\\two-comp-fit.res'
		resfile = 'X:\\AntonioP_t2\\RLadurner_JMPeters\\DoubleArrest_Noc\\150130_STAG2\\two-comp-fit.csv'
		#resfile = 'X:\\AntonioP_t2\\RLadurner_JMPeters\\DoubleArrest\\150120_STAG2\\FcsResults\\2c_LSM1_STAG2-mEGFP_H2B-mCherry.res'
		self.loadResultsFile(resfile)
		self.mygen = iter(self.fcsimages)
	

	def getPosition(self, xmlfile):
		''' Parse xml file for position of points and imgName. Returns a dictionary and imgName'''
		obj = {}
		tree = ET.parse(xmlfile)
		root = tree.getroot()
		for child in root:
			if child.tag == 'Image':
				imgName = os.path.join(os.path.dirname(xmlfile), os.path.basename(child.attrib['Name']))
				#legacy code
				fileName, fileExtension = os.path.splitext(imgName)
				if not fileExtension == '.czi' or not fileExtension == '.lsm':
					imgName = imgName + ".lsm"
			if child.tag == 'object':
				pos = [0, 0, 0]
				for nef in child:
					if nef.tag == 'x':
						pos[0] = int(nef.text)
					if nef.tag == 'y':
						pos[1] = int(nef.text)
					if nef.tag == 'z':
						pos[2] = int(nef.text)
				obj[int(child.attrib['ID'])] = pos
		return obj, imgName
		
	def loadResultsFile(self, resfile):
		my_file = open(resfile, 'r')
		my_file.seek(0)
		for line in my_file:
			tabLine = line.split('\t')
			if tabLine[0].isdigit():
				#first pt
				if re.search( 'R\d_P(\d)_K\d_Ch\d-Ch\d.zen', tabLine[1]).group(1) == '1':
					
					filename =  re.split('_R\d_P(\d)_K\d_Ch\d-Ch\d.zen', os.path.basename(tabLine[2]))[0] + '.xml'
					dirName = os.path.dirname(tabLine[2])
				
					dirName = dirName.replace("Z:", "X:")
					dirName = dirName.replace("Y:", "X:")
					
					filename = os.path.join(dirName,filename)
					
					fcspts, imgName = self.getPosition(filename)
					self.fcsimages.append([fcspts, imgName])


	
	def next(self, event):
		if self.idximg < -1:
			self.idximg = 0
		if self.idximg > len(self.fcsimages):
			self.idximg = len(self.fcsimages)
		else:
			self.idximg += 1
		print self.idximg
		self.showimage()
		
	def prev(self, event):
		if self.idximg <= 0:
			self.idximg = 0
		else:
			self.idximg -= 1
		self.showimage()
		
	def showimage(self):
		roim = RoiManager.getInstance()
		if roim is None:
			roim = RoiManager()
		IJ.run("Close All")
		IJ.run("Clear Results")
		try:
			roim.reset()
		except AttributeError:
			roim.runCommand("reset")
		obj = self.fcsimages[self.idximg][0]
		imgName = self.fcsimages[self.idximg][1]

		img =  BF.openImagePlus(imgName)[0]
		img.setZ(obj[1][2]+1)
		img.setC(3)
		IJ.run(img, "Grays", "");
		img.setC(1)
		img.show()

		#draw rois
		for i in range(1, len(obj)+1):
			PR = PointRoi(obj[i][0],obj[i][1])
			try:
				PR.setSize(3)
				PR.setPointType(0)
				roim.addRoi(PR)
			except:
				roim.addRoi(PR)
		roim.runCommand('Show All with Labels')
Esempio n. 56
0
        while results.next():
            i += 1
            #logger.debug("%s" % results)

            logger.debug("%s : %s" % (results.getString("TABLE_NAME"), results.getString("TABLE_TEXT")))

            #logger.debug("%s : %s [%s]" % (results.getString("COLUMN_NAME"), results.getString("COLUMN_TEXT"), results.getString("TYPE_NAME")))

            if i == 1000:
                exit()

        logger.debug("Success!")

def exit_all(event):
    exit

if __name__ == "__main__":
    f = JFrame('Hello, Jython!', defaultCloseOperation = JFrame.EXIT_ON_CLOSE, size = (550, 200))

    f.setResizable(True)

    b = JButton('Connect!', actionPerformed=change_text)
    #d = JButton('Exit!!', actionPerformed=exit_all)

    c = f.getContentPane()
    c.setBackground(Color.DARK_GRAY)
    c.add(b)
    #c.add(d)

    f.setVisible(True)