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
Example #2
0
def insertFloatFields(panel, gb, gc, params, strings):
  """
  strings: an array of arrays, which each array having at least 2 strings,
           with the first string being the title of the section,
           and subsequent strings being the label of the parameter
           as well as the key in the params dictionary to retrieve the value
           to show as default in the textfield.
  When a value is typed in and it is a valid float number, the entry in params is updated.
  When invalid, the text field background is turned red.
  """
  for block in strings:
    title = JLabel(block[0])
    gc.gridx = 0
    gc.gridy += 1
    gc.gridwidth = 2
    gc.anchor = GBC.WEST
    gb.setConstraints(title, gc)
    panel.add(title)
    for param in block[1:]:
      gc.gridy += 1
      gc.gridwidth = 1
      gc.gridx = 0
      gc.anchor = GBC.EAST
      name = JLabel(param + ": ")
      gb.setConstraints(name, gc)
      panel.add(name)
      gc.gridx = 1
      gc.anchor = GBC.WEST
      tf = JTextField(str(params[param]), 10)
      tf.addKeyListener(NumberTextFieldListener(param, params, parse=float))
      gb.setConstraints(tf, gc)
      panel.add(tf)
Example #3
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
Example #4
0
 def addDetails(self):
     jf0 = JFrame()
     jf0.setTitle("Add Issue");
     jf0.setLayout(None);
     
     txtEnterIssue = JTextField();
     txtEnterIssue.setName("Enter Issue Name");
     txtEnterIssue.setToolTipText("Enter Issue Name Here");
     txtEnterIssue.setBounds(182, 58, 473, 40);
     jf0.add(txtEnterIssue);
     txtEnterIssue.setColumns(10);
     
     btnNewButton = JButton("Add");
     btnNewButton.setBounds(322, 178, 139, 41);
     jf0.add(btnNewButton);
     
     comboBox = JComboBox();
     comboBox.setMaximumRowCount(20);
     comboBox.setEditable(True);
     comboBox.setToolTipText("Objective Name");
     comboBox.setBounds(182, 125, 473, 40);
     jf0.add(comboBox);
     
     lblNewLabel = JLabel("Issue Name Here");
     lblNewLabel.setFont(Font("Tahoma", Font.PLAIN, 16));
     lblNewLabel.setBounds(25, 58, 130, 40);
     jf0.add(lblNewLabel);
     
     lblNewLabel_1 = JLabel("Objective Name");
     lblNewLabel_1.setFont(Font("Tahoma", Font.PLAIN, 16));
     lblNewLabel_1.setBounds(25, 125, 130, 40);
     jf0.add(lblNewLabel_1);
     jf0.setVisible(True)
     jf0.setBounds(400, 300, 700, 300)
     jf0.EXIT_ON_CLOSE
     
     txtEnterIssue.addKeyListener(self)
Example #5
0
def makeCropUI(imp, images, tgtDir, panel=None, cropContinuationFn=None):
  """ imp: the ImagePlus to work on.
      images: the list of ImgLib2 images, one per frame, not original but already isotropic.
              (These are views that use a nearest neighbor interpolation using the calibration to scale to isotropy.)
      tgtDir: the target directory where e.g. CSV files will be stored, for ROI, features, pointmatches.
      panel: optional, a JPanel controlled by a GridBagLayout.
      cropContinuationFn: optional, a function to execute after cropping,
                          which is given as arguments the original images,
                          minC, maxC (both define a ROI), and the cropped images. """
  independent = None == panel
  if not panel:
    panel = JPanel()
    panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
    gb = GridBagLayout()
    gc = GBC()
  else:
    gb = panel.getLayout()
    # Constraints of the last component
    gc = gb.getConstraints(panel.getComponent(panel.getComponentCount() - 1))
    
    # Horizontal line to separate prior UI components from crop UI
    gc.gridx = 0
    gc.gridy += 1
    gc.gridwidth = 4
    gc.anchor = GBC.WEST
    gc.fill = GBC.HORIZONTAL
    sep = JSeparator()
    sep.setMinimumSize(Dimension(200, 10))
    gb.setConstraints(sep, gc)
    panel.add(sep)

  # ROI UI header
  title = JLabel("ROI controls:")
  gc.gridy +=1
  gc.anchor = GBC.WEST
  gc.gridwidth = 4
  gb.setConstraints(title, gc)
  panel.add(title)

  # Column labels for the min and max coordinates
  gc.gridy += 1
  gc.gridwidth = 1
  for i, title in enumerate(["", "X", "Y", "Z"]):
    gc.gridx = i
    gc.anchor = GBC.CENTER
    label = JLabel(title)
    gb.setConstraints(label, gc)
    panel.add(label)

  textfields = []
  rms = []

  # Load stored ROI if any
  roi_path = path = os.path.join(tgtDir, "crop-roi.csv")
  if os.path.exists(roi_path):
    with open(roi_path, 'r') as csvfile:
      reader = csv.reader(csvfile, delimiter=',', quotechar="\"")
      reader.next() # header
      minC = map(int, reader.next()[1:])
      maxC = map(int, reader.next()[1:])
      # Place the ROI over the ImagePlus
      imp.setRoi(Roi(minC[0], minC[1], maxC[0] + 1 - minC[0], maxC[1] + 1 - minC[1]))
  else:
    # Use whole image dimensions
    minC = [0, 0, 0]
    maxC = [v -1 for v in Intervals.dimensionsAsLongArray(images[0])]

  # Text fields for the min and max coordinates
  for rowLabel, coords in izip(["min coords: ", "max coords: "],
                               [minC, maxC]):
    gc.gridx = 0
    gc.gridy += 1
    label = JLabel(rowLabel)
    gb.setConstraints(label, gc)
    panel.add(label)
    for i in xrange(3):
      gc.gridx += 1
      tf = JTextField(str(coords[i]), 10)
      gb.setConstraints(tf, gc)
      panel.add(tf)
      textfields.append(tf)
      listener = RoiMaker(imp, textfields, len(textfields) -1)
      rms.append(listener)
      tf.addKeyListener(listener)
      tf.addMouseWheelListener(listener)

  # Listen to changes in the ROI of imp
  rfl = RoiFieldListener(imp, textfields)
  Roi.addRoiListener(rfl)
  # ... and enable cleanup
  ImagePlus.addImageListener(FieldDisabler(rfl, rms))

  # Functions for cropping images
  cropped = None
  cropped_imp = None

  def storeRoi(minC, maxC):
    if os.path.exists(roi_path):
      # Load ROI
      with open(path, 'r') as csvfile:
        reader = csv.reader(csvfile, delimiter=',', quotechar="\"")
        reader.next() # header
        same = True
        for a, b in izip(minC + maxC, map(int, reader.next()[1:] + reader.next()[1:])):
          if a != b:
            same = False
            # Invalidate any CSV files for features and pointmatches: different cropping
            for filename in os.listdir(tgtDir):
              if filename.endswith("features.csv") or filename.endswith("pointmatches.csv"):
                os.remove(os.path.join(tgtDir, filename))
            break
        if same:
          return
    # Store the ROI as crop-roi.csv
    with open(roi_path, 'w') as csvfile:
      w = csv.writer(csvfile, delimiter=',', quotechar="\"", quoting=csv.QUOTE_NONNUMERIC)
      w.writerow(["coords", "x", "y", "z"])
      w.writerow(["min"] + map(int, minC))
      w.writerow(["max"] + map(int, maxC))
  
  def crop(event):
    global cropped, cropped_imp
    coords = [int(float(tf.getText())) for tf in textfields]
    minC = [max(0, c) for c in coords[0:3]]
    maxC = [min(d -1, c) for d, c in izip(Intervals.dimensionsAsLongArray(images[0]), coords[3:6])]
    storeRoi(minC, maxC)
    print "ROI min and max coordinates"
    print minC
    print maxC
    cropped = [Views.zeroMin(Views.interval(img, minC, maxC)) for img in images]
    cropped_imp = showAsStack(cropped, title="cropped")
    cropped_imp.setDisplayRange(imp.getDisplayRangeMin(), imp.getDisplayRangeMax())
    if cropContinuationFn:
      cropContinuationFn(images, minC, maxC, cropped, cropped_imp)

  # Buttons to create a ROI and to crop to ROI,
  # which when activated enables the fine registration buttons
  crop_button = JButton("Crop to ROI")
  crop_button.addActionListener(crop)
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 4
  gc.anchor = GBC.WEST
  buttons_panel = JPanel()
  buttons_panel.add(crop_button)
  gb.setConstraints(buttons_panel, gc)
  panel.add(buttons_panel)

  if independent:
    frame = JFrame("Crop by ROI")
    frame.getContentPane().add(panel)
    frame.pack()
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
    frame.addWindowListener(CloseControl(destroyables=rms + [rfl]))
    frame.setVisible(True)
  else:
    # Re-pack the JFrame
    parent = panel.getParent()
    while not isinstance(parent, JFrame) and parent is not None:
      parent = parent.getParent()

    if parent:
      frame = parent
      frame.pack()
      found = False
      for wl in frame.getWindowListeners():
        if isinstance(wl, CloseControl):
          wl.addDestroyables(rms + [rfl])
          found = True
          break
      if not found:
        frame.addWindowListener(CloseControl(destroyables=rms + [rfl]))
      frame.setVisible(True)

  return panel
Example #6
0
def makeTranslationUI(affines, imp, show=True, print_button_text="Print transforms"):
  """
  A GUI to control the translation components of a list of AffineTransform3D instances.
  When updated, the ImagePlus is refreshed.

  affines: a list (will be read multiple times) of one affine transform per image.
  imp: the ImagePlus that hosts the virtual stack with the transformed images.
  show: defaults to True, whether to make the GUI visible.
  print_button_text: whatever you want the print button to read like, defaults to "Print transforms".
   
  Returns the JFrame, the main JPanel and the lower JButton panel.
  """
  panel = JPanel()
  panel.setBorder(BorderFactory.createEmptyBorder(10,10,10,10))
  gb = GridBagLayout()
  panel.setLayout(gb)
  gc = GBC()
  gc.anchor = GBC.WEST
  gc.fill = GBC.NONE

  # Column labels
  gc.gridy = 0
  for i, title in enumerate(["Camera", "translation X", "translation Y", "translation Z"]):
    gc.gridx = i
    gc.anchor = GBC.CENTER
    label = JLabel(title)
    gb.setConstraints(label, gc)
    panel.add(label)

  gc.anchor = GBC.WEST
  listeners = []
  
  # One row per affine to control: skip the first
  for i, affine in enumerate(affines[1:]):
    gc.gridx = 0
    gc.gridy += 1
    label = JLabel("CM0%i: " % (i + 1))
    gb.setConstraints(label, gc)
    panel.add(label)
    # One JTextField per dimension
    for dimension, translation in enumerate(affine.getTranslation()):
      tf = JTextField(str(translation), 10)
      listener = MatrixTextFieldListener(affine, dimension, tf, imp)
      listeners.append(listener)
      imp.addImageListener(listener) # to disable the JTextField when closed
      tf.addKeyListener(listener)
      tf.addMouseWheelListener(listener)
      gc.gridx += 1
      gb.setConstraints(tf, gc)
      panel.add(tf)

  # Documentation for the user
  help_lines = ["Type a number and push enter,",
                "or use the scroll wheel."]
  gc.gridx = 0
  gc.gridwidth = 4
  for line in help_lines:
    gc.gridy += 1
    help = JLabel(line)
    gb.setConstraints(help, gc)
    panel.add(help)

  # Buttons
  printButton = JButton(print_button_text)
  
  def printTransforms(event):
    for i, aff in enumerate(affines): # print all, including the first
      matrix = zeros(12, 'd')
      aff.toArray(matrix)
      msg = "# Coarse affine matrix " + str(i) + ": \n" + \
            "affine" + str(i) + ".set(*[%f, %f, %f, %f,\n %f, %f, %f, %f,\n %f, %f, %f, %f])" % tuple(matrix.tolist())
      # Print everywhere
      print msg
      IJ.log(msg)
      System.out.println(msg)
      
  
  printButton.addActionListener(printTransforms)
  gc.gridx = 0
  gc.gridy += 1
  gc.gridwidth = 4
  button_panel = JPanel()
  button_panel.add(printButton)
  gb.setConstraints(button_panel, gc)
  panel.add(button_panel)

  frame = JFrame("Translation control")
  frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE)
  frame.addWindowListener(CloseControl(destroyables=listeners))
  frame.getContentPane().add(panel)
  frame.pack()
  frame.setLocationRelativeTo(None) # center in the screen
  frame.setVisible(show)

  return frame, panel, button_panel
Example #7
0
    class ConsoleController:
        def __init__(self, parent):
            self._parent = parent
            self._sessions = self._parent.sessions()
            self._request = None #TODO I'll need a request in order to connect to something
            self._position = None #TODO I'll need a position, something to change in the header to insert the command
            self._pwd = None
            self._commandHistory = []
            self._historyIndex = 0
            self._tabComplete = []

        def getMainComponent(self):
            self._mainPanel = JPanel(BorderLayout())
            # input
            self._consolePwd = JTextField()
            self._consolePwd.setEditable(False)
            self._consolePwd.setText("Not initialized")
            self._consoleInput = JTextField()
            #Remove 'tab' low-level tab-function of jumping to other component, so I can use it
            self._consoleInput.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET)
            self._consoleInput.addActionListener(self.EnterPress())
            self._consoleInput.addKeyListener(self.KeyPress())
            self._inputPanel = JPanel(BorderLayout())
            self._inputPanel.add(self._consolePwd, BorderLayout.WEST)
            self._inputPanel.add(self._consoleInput, BorderLayout.CENTER)
            # output
            self._consoleOutput = JTextArea()
            self._consoleOutput.setEditable(False)
            self._consoleOutput.setForeground(Color.WHITE)
            self._consoleOutput.setBackground(Color.BLACK)
            self._consoleOutput.setFont(self._consoleOutput.getFont().deriveFont(12.0))

            self._scrollPaneConsoleOutput = JScrollPane(self._consoleOutput)

            # Add to main panel and return the main panel
            self._mainPanel.add(self._scrollPaneConsoleOutput, BorderLayout.CENTER)
            self._mainPanel.add(self._inputPanel, BorderLayout.SOUTH)
            return self._mainPanel

        def sendCommand(self, requestId, cmd, directTo):
            Utils.out("ConsoleController > sendCommand > 'cmd'")
            Utils.out(cmd)
            if cmd == 'clear':
                self.resetOutput()
                self._commandHistory.append(cmd)
                self.resetHistoryIndex()
                self.clearCmd()
                return
            cmdModified = cmd
            requestHttpMethod = self._parent.getRequestHttpService(requestId)
            #If I use virtual persistence and there's already a pwd set
            if Utils.shellController._virtualPersistence and self.pwd():
                #Then always prepend 'cd <pwd>' to any command executed. In reality we
                # always enter in the same directory, but because this shell keeps track
                # of where the user thinks he is, and always goes to that directory first
                # the illusion of a persistence is created
                cmdVirtual = "cd " + self.pwd()
                cmdModified = cmdVirtual + "; " + cmd
            requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdModified)
            Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, directTo)).start()
            self._commandHistory.append(cmd)
            self.resetHistoryIndex()
            self.clearCmd()

            if Utils.shellController._virtualPersistence:
                if cmd.startswith('cd '):
                    Utils.out("ConsoleController > sendCommand: detected 'cd '")
                    #ask for pwd
                    cmdPwd = cmdModified + "; " + Commands.pwd(Commands.OS_LINUX)
                    requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdPwd)
                    Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'pwd')).start()
                if Utils.shellController._tabCompletion:
                    #ask 'ls -1a' for tab-completion
                    # The first command, pwd is set here, but cmdVirtual ain't. But this
                    # also means we are at the entry directory anyway, so we can just ask ls
                    # and get the correct tab completion anyway
                    try:
                        cmdTabComplete = cmdVirtual + "; " + Commands.ls(Commands.OS_LINUX)
                    except:
                        cmdTabComplete = Commands.ls(Commands.OS_LINUX)
                    requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdTabComplete)
                    Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'tabComplete')).start()
            else:
                if Utils.shellController._tabCompletion:
                    cmdTabComplete = Commands.ls(Commands.OS_LINUX)
                    requestWithCommand = self._parent.getRequestWithCommand(requestId, cmdTabComplete)
                    Thread(GetThreadForRequest(requestHttpMethod, requestWithCommand, 'tabComplete')).start()

            #either way execute the requested command

        def startSession(self):
            #TODO when starting a session I want to test for a number of things:
            # if I can reform the request to a post request and still have it work
            # if base 64 is available
            # if bash is available
            self.setPwd(None)
            if Utils.shellController._virtualPersistence and Utils.shellController._outputIsolator:
                Utils.out("startSession > virtualPersistence enabled > Requesting pwd")
                self.sendCommand(self._parent.currentRequestId(), Commands.pwd(Commands.OS_LINUX), 'pwd')

        def appendOutput(self, text, printCommand=True):
            try:
                if printCommand:
                    self.printCommand(self._commandHistory[-1])
            except:
                pass

            self._consoleOutput.append("\n" + text)
            #auto scroll down if needed
            self._consoleOutput.setCaretPosition(self._consoleOutput.getDocument().getLength())

        def resetOutput(self):
            Utils.setConsole('')

        def printCommand(self, cmd):
            self._consoleOutput.append("\n" + self._pwd + "# " + cmd)

        def printCurrentCommand(self):
            self.printCommand(self.cmd())

        def setPwd(self, pwd):
            self._pwd = pwd
            if pwd is None:
                self._consolePwd.setText('')
            else:
                self._consolePwd.setText(pwd)
            Utils.consoleController._mainPanel.revalidate()

        def pwd(self):
            return self._pwd

        def cmdHistoryCount(self):
            return len(self._commandHistory) #TODO - 1

        def setCmd(self, cmd):
            self._consoleInput.setText(cmd)

        def cmd (self):
            return self._consoleInput.getText()

        def clearCmd(self):
            self._consoleInput.setText('')

        def resetHistoryIndex(self):
            self._historyIndex = self.cmdHistoryCount()

        def previousCommand(self):
            if self._historyIndex > 0:
                self._historyIndex -= 1
                self.setCmd(self._commandHistory[self._historyIndex])

        def nextCommand(self):
            if self._historyIndex < self.cmdHistoryCount():
                self._historyIndex += 1
                self.setCmd(self._commandHistory[self._historyIndex])
            else:
                self.clearCmd()
                self.resetHistoryIndex()

        def setTabComplete(self, text):
            self._tabComplete = text.splitlines()

        def findTabComplete(self, beginCharacters=''):
            suggestions = []
            if beginCharacters:
                for suggestion in self._tabComplete:
                    Utils.debug("suggestion", suggestion)
                    Utils.debug("text", beginCharacters)
                    if suggestion[0:len(beginCharacters)] == beginCharacters:
                        suggestions.append(suggestion)
            else:
                suggestions = self._tabComplete
            return suggestions

        def tabComplete(self):
            currentCommand = self.cmd()
            Utils.debug("currentCommand", currentCommand)
            if currentCommand:
                commandArray = currentCommand.split(' ')
                lastword = commandArray.pop()
                Utils.debug("lastword", lastword)
                suggestions = self.findTabComplete(lastword)
                if suggestions:
                    if len(suggestions) > 1:
                        self.printCurrentCommand()
                        for suggestion in suggestions:
                            self.appendOutput(suggestion, False)
                    if len(suggestions) == 1:
                        self.setCmd(' '.join(commandArray) + ' ' + suggestions.pop())
            else:
                suggestions = self.findTabComplete()
                if len(suggestions) > 1:
                    self.printCurrentCommand()
                    for suggestion in suggestions:
                        self.appendOutput(suggestion, False)

        class EnterPress(ActionListener): #TODO remove: AbstractAction
            def actionPerformed(self, e):
                Utils.consoleController.sendCommand(Utils.shellController.currentRequestId(), Utils.consoleInput.getText(), 'console')

            def keyPressed(self, e):
                Utils.out("key pressed")

        class KeyPress(KeyListener):
            def keyTyped(self, e):
                pass

            def keyReleased(self, e):
                if e.getKeyCode() == e.VK_DOWN:
                    Utils.consoleController.nextCommand()
                    Utils.out("released down")
                if e.getKeyCode() == e.VK_UP:
                    Utils.consoleController.previousCommand()
                    Utils.out("released up")

                if e.getKeyCode() == e.VK_TAB:
                    Utils.out("pressed tab")
                    Utils.consoleController.tabComplete()

            def keyPressed(self, e):
                pass
Example #8
0
def specifyRoiUI(roi=Roi(0, 0, 0, 0)):
    # A panel in which to place UI elements
    panel = JPanel()
    panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10))
    gb = GridBagLayout()
    panel.setLayout(gb)
    gc = GBC()

    bounds = roi.getBounds() if roi else Rectangle()
    textfields = []
    roimakers = []

    # Basic properties of most UI elements, will edit when needed
    gc.gridx = 0  # can be any natural number
    gc.gridy = 0  # idem.
    gc.gridwidth = 1  # when e.g. 2, the UI element will occupy two horizontally adjacent grid cells
    gc.gridheight = 1  # same but vertically
    gc.fill = GBC.NONE  # can also be BOTH, VERTICAL and HORIZONTAL

    for title in ["x", "y", "width", "height"]:
        # label
        gc.gridx = 0
        gc.anchor = GBC.EAST
        label = JLabel(title + ": ")
        gb.setConstraints(label, gc)  # copies the given constraints 'gc',
        # so we can modify and reuse gc later.
        panel.add(label)
        # text field, below the title
        gc.gridx = 1
        gc.anchor = GBC.WEST
        text = str(getattr(bounds,
                           title))  # same as e.g. bounds.x, bounds.width, ...
        textfield = JTextField(text,
                               10)  # 10 is the size of the field, in digits
        gb.setConstraints(textfield, gc)
        panel.add(textfield)
        textfields.append(
            textfield)  # collect all 4 created textfields for the listeners
        # setup ROI and text field listeners
        listener = RoiMaker(textfields,
                            len(textfields) -
                            1)  # second argument is the index of textfield
        # in the list of textfields.
        roimakers.append(listener)
        textfield.addKeyListener(listener)
        textfield.addMouseWheelListener(listener)
        # Position next ROI property in a new row by increasing the Y coordinate of the layout grid
        gc.gridy += 1

    # User documentation (uses HTML to define line breaks)
    doc = JLabel(
        "<html><body><br />Click on a field to activate it, then:<br />" +
        "Type in integer numbers<br />" +
        "or use arrow keys to increase by 1<br />" +
        "or use the scroll wheel on a field.</body></html>")
    gc.gridx = 0  # start at the first column
    gc.gridwidth = 2  # Spans both columns
    gb.setConstraints(doc, gc)
    panel.add(doc)

    # Listen to changes in the ROI of imp
    roilistener = TextFieldUpdater(textfields)
    Roi.addRoiListener(roilistener)

    # Show window
    frame = JFrame("Specify rectangular ROI")
    frame.getContentPane().add(panel)
    frame.pack()
    frame.setLocationRelativeTo(None)  # center in the screen
    frame.setDefaultCloseOperation(
        JFrame.DO_NOTHING_ON_CLOSE)  # prevent closing the window
    frame.addWindowListener(
        CloseControl(roilistener))  # handles closing the window
    frame.setVisible(True)
Example #9
0
class _HintTextField(FocusListener, KeyAdapter):
    """
    HintTextField is a class responsible for showing an hint while the textfield is empty
    """
    def __init__(self, hint=None, action=None):
        if not hint: hint = 'hint'
        if not action: action = nop_evt
        self.this = JTextField(hint)
        self._hint = hint
        self._showing_hint = True
        self._enter_listener = None
        self.this.addFocusListener(self)
        self.this.addKeyListener(self)
        self.set_enter_evt_listener(action)

    def set_enter_evt_listener(self, enter_listener):
        """
        Add an evt listener to HintTextField

        :param enter_listener: lambda event listener
        :return:
        """
        self._enter_listener = enter_listener

    def keyPressed(self, e):
        """
        KeyAdapter override

        :param e: event containing the key pressed
        :return: None
        """
        if self._enter_listener and e.getKeyCode() == KeyEvent.VK_ENTER:
            self._enter_listener(e)

    def focusGained(self, e):
        """
        FocusListener override

        :param e: unused
        :return: None
        """
        if self.getText() == "":
            self.this.setText("")
            self._showing_hint = False

    def focusLost(self, e):
        """
        FocusListener override

        :param e: unused
        :return: None
        """
        if self.getText() == "":
            self.this.setText(self._hint)
            self._showing_hint = True

    def getText(self):
        """
        :return: the current text or "" if no text is wrote inside the textfield
        """
        if self._showing_hint:
            return ""
        else:
            return self.this.getText()

    def setText(self, txt):
        """
        Set Text

        :param txt: a string
        :return: None
        """
        self.this.setText(txt)
        self._showing_hint = False

    def reset(self):
        """
        Reset the HintBox
        :return: None
        """
        self.this.setText(self._hint)
        self._showing_hint = True
Example #10
0
class ConsolePanel(Panel):
    def __init__(self):

        self.console = None
        self.outText = None
        self.inText = None
        self.outTextScroller = None
        self.nestedInputPanel = None
        self.directoryText = None
        Panel.__init__(self, "insets 0 0 0 0")

    def sendCommand(self, command):
        print str(self)
        oldText = self.inText.getText()
        self.inText.setText(command)

        self.inText.getActionListeners()[0].actionPerformed(None)
        self.inText.setText(oldText)

    def setDirectoryText(self, dirText):
        self.directoryText.setText(dirText)
        self.nestedInputPanel.revalidate()

    def write_out(self, text):
        if not self.outText:
            return
        self.outText.setText(self.outText.getText() + text)

    def initUI(self):

        font = Font("Courier New", Font.BOLD, 14)

        #create the output text panel
        self.outText = JTextArea()
        self.outText.setEditable(False)
        self.outText.setFont(font)
        self.outText.setWrapStyleWord(True)
        self.outText.setLineWrap(True)

        #self.outText.setLineWrap(True)
        #self.outText.setWrapStyleWord(True)
        class NoGhostScroller(JScrollPane):
            def paintComponent(self, g):

                g.setColor(self.getBackground())
                g.fillRect(0, 0, self.getWidth(), self.getHeight())
                #super(NoGhostScroller, self).paintComponent(g)

        self.outTextScroller = JScrollPane(self.outText)
        self.outTextScroller.setHorizontalScrollBarPolicy(
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER)
        self.outTextScroller.getVerticalScrollBar().setForeground(
            Color(255, 0, 0))
        #self.outText.setOpaque(False)
        self.outText.setBackground(Color(0, 20, 0))
        self.outText.setForeground(Color.WHITE)

        #self.outTextScroller.setOpaque(False)
        self.outTextScroller.setBackground(Color(0, 20, 0))

        #self.outText.repaint()

        #self.layered = JLayeredPane()
        #self.layered.setLayer(self.outTextScroller, 0)

        #create the input text box
        self.inText = JTextField()
        self.inText.setFocusTraversalKeysEnabled(False)
        self.inText.setFont(font)
        self.inText.setBackground(Color(0, 20, 0))
        self.inText.setForeground(Color.WHITE)
        self.inText.getCaret().setVisible(True)
        self.inText.getCaret().setBlinkRate(500)
        self.inText.setCaretColor(Color(200, 255, 200))

        class InFocusAdapter(FocusAdapter):
            def focusLost(adap, e):
                self.inText.setVisible(True)

        self.inText.addFocusListener(InFocusAdapter())

        self.nestedInputPanel = Panel("Insets 0 0 0 0")

        #create the directory text box
        self.directoryText = JTextField()
        self.directoryText.setEditable(False)
        self.directoryText.setFont(font)
        self.directoryText.setBackground(Color(0, 20, 0))
        self.directoryText.setForeground(Color.WHITE)
        #set up the console
        sys.stdout = FakeOut(self.outText)
        self.console = BashED_Console(stdout=sys.stdout)
        self.directoryText.setText(self.console.get_prompt())
        self.revalidate()

        dirTex = self.directoryText

        #create the listener that fires when the 'return' key is pressed
        class InputTextActionListener(ActionListener):
            def __init__(self, parent, inp, out, console):
                self.parent = parent
                self.inp = inp
                self.out = out
                self.console = console

            def actionPerformed(self, e):
                #print self.getCommandText()
                # print(self.console.get_prompt())
                # self.console.onecmd(self.inp.getText())
                # self.parent.write_out("\n" + self.inp.getText())
                # dirTex.setText(self.console.get_prompt())
                # self.inp.setText("")

                self.parent.write_out(self.console.get_prompt() +
                                      self.inp.getText() + '\n')
                if 'clear' in self.inp.getText().split(' ')[0]:
                    self.out.setText("")  #clear the screen
                else:
                    self.console.onecmd(self.inp.getText())

                dirTex.setText(self.console.get_prompt())
                self.inp.setText("")

        #create the listener that fires whenever a user hits a key
        class InputKeyActionListener(KeyAdapter):
            def __init__(self, parent, inp, out, console):
                self.parent = parent
                self.inp = inp
                self.out = out
                self.console = console

            def keyReleased(self, k):
                inp = self.inp.getText()
                if k.getKeyCode() == 9:  #tab character
                    autos = self.console.tabcomplete(self.inp.getText())
                    if len(autos) == 1:
                        self.inp.setText(autos[0])
                    else:
                        i = 0
                        for option in autos:
                            self.parent.write_out(option)
                            if i % 3 == 0:
                                print('\n')
                            else:
                                print('\t')
                hist = None
                if k.getKeyCode() == 38:
                    hist = self.console.next_hist()
                if k.getKeyCode() == 40:
                    hist = self.console.last_hist()

                if hist:
                    self.inp.setText(hist.rstrip('\n'))  #prevent from firing

        self.inText.addActionListener(
            InputTextActionListener(self, self.inText, self.outText,
                                    self.console))
        self.inText.addKeyListener(
            InputKeyActionListener(self, self.inText, self.outText,
                                   self.console))

    def addUI(self):

        self.add(self.outTextScroller, "cell 0 0, push, grow")
        self.add(self.nestedInputPanel, "cell 0 1, pushx, growx")
        self.nestedInputPanel.add(self.directoryText, "cell 0 0")
        self.nestedInputPanel.add(self.inText, "cell 1 0, spanx, pushx, growx")
        SwingUtilities.invokeLater(
            lambda: table.updateUI())  # executed by the event dispatch thread
    except:
        print "Malformed regex pattern"


class TypingInSearchField(KeyAdapter):
    def keyPressed(self, event):
        if KeyEvent.VK_ENTER == event.getKeyCode():
            filterTable()
        elif KeyEvent.VK_ESCAPE == event.getKeyCode():
            search_field.setText("")
            filterTable()  # to restore the full list of rows


search_field.addKeyListener(TypingInSearchField())


# Function for the button to open the folder containing the image file path in the selected table row
class OpenAtFolder(ActionListener):
    def actionPerformed(self, event):
        if 0 == path.getText().find("http"):
            IJ.showMessage("Can't open folder: it's an URL")
            return
        directory = os.path.dirname(path.getText())
        od = OpenDialog("Open", directory, None)
        filepath = od.getPath()
        if filepath:
            IJ.open(filepath)

Example #12
0
class ConsolePanel(Panel):

	def __init__(self):
		
		self.console = None
		self.outText = None
		self.inText = None
		self.outTextScroller = None
		self.nestedInputPanel = None
		self.directoryText = None
		Panel.__init__(self, "insets 0 0 0 0")

	def sendCommand(self, command):
		print str(self)
		oldText = self.inText.getText()
		self.inText.setText(command)

		self.inText.getActionListeners()[0].actionPerformed(None)
		self.inText.setText(oldText)

	def setDirectoryText(self, dirText):
		self.directoryText.setText(dirText)
		self.nestedInputPanel.revalidate()

	def write_out(self,text):
		if not self.outText:
			return
		self.outText.setText(self.outText.getText() + text)

	def initUI(self):

		font = Font("Courier New", Font.BOLD, 14)

		#create the output text panel
		self.outText = JTextArea()
		self.outText.setEditable(False)
		self.outText.setFont(font)
		self.outText.setWrapStyleWord(True)
		self.outText.setLineWrap(True)
		#self.outText.setLineWrap(True)
		#self.outText.setWrapStyleWord(True)
		class NoGhostScroller(JScrollPane):
			def paintComponent(self, g):
				
				g.setColor(self.getBackground())
				g.fillRect(0, 0, self.getWidth(), self.getHeight())
				#super(NoGhostScroller, self).paintComponent(g)

		self.outTextScroller = JScrollPane(self.outText)
		self.outTextScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER)
		self.outTextScroller.getVerticalScrollBar().setForeground(Color(255, 0, 0))
		#self.outText.setOpaque(False)
		self.outText.setBackground(Color(0, 20, 0))
		self.outText.setForeground(Color.WHITE)

		#self.outTextScroller.setOpaque(False)
		self.outTextScroller.setBackground(Color(0, 20, 0))

		#self.outText.repaint()

		#self.layered = JLayeredPane()
		#self.layered.setLayer(self.outTextScroller, 0)

		#create the input text box
		self.inText = JTextField()
		self.inText.setFocusTraversalKeysEnabled(False)
		self.inText.setFont(font)
		self.inText.setBackground(Color(0, 20, 0))
		self.inText.setForeground(Color.WHITE)
		self.inText.getCaret().setVisible(True)
		self.inText.getCaret().setBlinkRate(500)
		self.inText.setCaretColor(Color(200,255,200))
		
		class InFocusAdapter(FocusAdapter):
			def focusLost(adap, e):
				self.inText.setVisible(True)
		self.inText.addFocusListener(InFocusAdapter())

		self.nestedInputPanel = Panel("Insets 0 0 0 0")

		#create the directory text box
		self.directoryText = JTextField()
		self.directoryText.setEditable(False)
		self.directoryText.setFont(font)
		self.directoryText.setBackground(Color(0, 20, 0))
		self.directoryText.setForeground(Color.WHITE)
		#set up the console
		sys.stdout = FakeOut(self.outText)
		self.console = BashED_Console(stdout=sys.stdout)
		self.directoryText.setText(self.console.get_prompt())
		self.revalidate();


		dirTex = self.directoryText;

		#create the listener that fires when the 'return' key is pressed
		class InputTextActionListener(ActionListener):
			def __init__(self,parent,inp,out,console):
				self.parent = parent
				self.inp = inp
				self.out = out
				self.console = console

			def actionPerformed(self, e):
				#print self.getCommandText()
				# print(self.console.get_prompt())
				# self.console.onecmd(self.inp.getText())
				# self.parent.write_out("\n" + self.inp.getText())
				# dirTex.setText(self.console.get_prompt())
				# self.inp.setText("")

				self.parent.write_out(self.console.get_prompt() + self.inp.getText() + '\n')
				if 'clear' in self.inp.getText().split(' ')[0]:
					self.out.setText("") #clear the screen
				else:
					self.console.onecmd(self.inp.getText())
				
				dirTex.setText(self.console.get_prompt())
				self.inp.setText("")

		#create the listener that fires whenever a user hits a key
		class InputKeyActionListener(KeyAdapter):
			def __init__(self,parent,inp,out,console):
				self.parent = parent
				self.inp = inp
				self.out = out
				self.console = console

			def keyReleased(self, k):
				inp = self.inp.getText()
				if k.getKeyCode() == 9: #tab character
					autos = self.console.tabcomplete(self.inp.getText())
					if len(autos) == 1:
						self.inp.setText(autos[0])
					else:
						i = 0
						for option in autos:
							self.parent.write_out(option)
							if i % 3 == 0:
								print('\n')
							else:
								print('\t')
				hist = None
				if k.getKeyCode() == 38:
					hist = self.console.next_hist()
				if k.getKeyCode() == 40:
					hist = self.console.last_hist()

				if hist:
					self.inp.setText(hist.rstrip('\n'))#prevent from firing

		self.inText.addActionListener(InputTextActionListener(self,self.inText,self.outText,self.console))
		self.inText.addKeyListener(InputKeyActionListener(self,self.inText,self.outText,self.console))




	def addUI(self):
		
		self.add(self.outTextScroller, "cell 0 0, push, grow")
		self.add(self.nestedInputPanel, "cell 0 1, pushx, growx")
		self.nestedInputPanel.add(self.directoryText, "cell 0 0")
		self.nestedInputPanel.add(self.inText, "cell 1 0, spanx, pushx, growx")