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
def getContentPane(): global contentPane global REMAP_WIDTH global REMAP_HEIGHT global MARGIN if not contentPane: global mainScreen global mainScreenImg mainScreen = JLabel() cursorImg = BufferedImage(16,16,BufferedImage.TYPE_INT_ARGB) blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(cursorImg, Point(0,0), "blank cursor") mainScreen.setCursor(blankCursor) mainScreen.setPreferredSize( Dimension(REMAP_WIDTH + MARGIN, REMAP_HEIGHT + MARGIN)) mainScreen.setText("main screen!") image = BufferedImage(REMAP_WIDTH + MARGIN, REMAP_HEIGHT + MARGIN , BufferedImage.TYPE_INT_ARGB) g = image.createGraphics() g.setColor(Color.BLACK) g.fillRect(0, 0, REMAP_WIDTH + MARGIN, REMAP_HEIGHT + MARGIN) g.setColor(Color.WHITE) g.setFont(Font("Serif", Font.BOLD, 20)) g.drawString("Cursor will display on your device.", 50, 30) mainScreenImg = image mainScreen.setIcon(swing.ImageIcon(image)) mouseListener = ScrMouseListener() mainScreen.addMouseListener(mouseListener) mainScreen.addMouseMotionListener(mouseListener) mainScreen.addMouseWheelListener(mouseListener) keyListener = ScrKeyListener() mainScreen.addKeyListener(keyListener) mainScreen.setFocusable(True) scrPanel = JPanel() scrPanel.setLayout(BoxLayout(scrPanel, BoxLayout.Y_AXIS)) scrPanel.add(mainScreen) contentPane = JPanel() contentPane.setLayout(BorderLayout()) contentPane.add(scrPanel, BorderLayout.WEST) # contentPAne.add(controlPanel(). BorderLayout.EAST) return contentPane
class BurpExtender(IBurpExtender, IContextMenuFactory, ITab, IExtensionStateListener, IMessageEditorController, IHttpListener): ''' IBurpExtender: Hook into burp and inherit base classes ITab: Create new tabs inside burp IMessageEditorTabFactory: Access createNewInstance ''' def registerExtenderCallbacks(self, callbacks): # Set encoding to utf-8 to avoid some errors reload(sys) sys.setdefaultencoding('utf8') # Keep a reference to callback object and helper object self._callbacks = callbacks self._helpers = callbacks.getHelpers() # Set the extension name that shows in the burp extension menu callbacks.setExtensionName("InjectionScanner") # Create the log and a lock on which to synchronize when adding log entries self._log = ArrayList() self._logLock = Lock() self._httpLock = Lock() # The length of the basis used to fetch abnormal data, default to zero self._basisLen = 0 # 1: {POST. GET}; 2: {urlencoded, json, xml} self._postGet = 'NaN' self._dataType = 'NaN' # Scan list self._simpleList = [ '\'', '\"', '/', '/*', '#', ')', '(', ')\'', '(\'', 'and 1=1', 'and 1=2', 'and 1>2', 'and 12', '+', 'and+12', '/**/and/**/1' ] self._xmlList = ['a', 'b', 'c', 'd', 'e'] # Not setted # Response mutex: True = is blocking; False = free to go # self._mutexR = False # Other classes instance self._dataTable = Guis_DefaultTM() self._logTable = Guis_AbstractTM(self) self._xh = XMLHandler() listeners = Guis_Listeners(self, self._logTable) ''' Setting GUIs ''' # Divide the whole pane two: one upper and one lower pane self._mainSplitpane = JSplitPane(JSplitPane.VERTICAL_SPLIT) self._mainSplitpane.setResizeWeight(0.4) # Initizlize request table dataTable = JTable(self._dataTable) dataScrollPane = JScrollPane(dataTable) dataScrollPane.setPreferredSize(Dimension(0, 125)) self._dataTable.addTableModelListener(listeners) # Initialize log table logTable = Guis_LogTable(self._logTable) logScrollPane = JScrollPane(logTable) logScrollPane.setPreferredSize(Dimension(0, 125)) # Split the upper pane to two panes tableSplitpane = JSplitPane(JSplitPane.HORIZONTAL_SPLIT) tableSplitpane.setResizeWeight(0.5) # Set the data table to the left and log to the right tableSplitpane.setLeftComponent(dataScrollPane) tableSplitpane.setRightComponent(logScrollPane) # Tabs with request/response viewers tabs = JTabbedPane() self._requestViewer = callbacks.createMessageEditor(self, False) self._responseViewer = callbacks.createMessageEditor(self, False) tabs.addTab("Request", self._requestViewer.getComponent()) tabs.addTab("Response", self._responseViewer.getComponent()) # Create buttons that do operation with the test self._basisLabel = JLabel('Basis: ' + str(self._basisLen)) self._levelLabel = JLabel('Level:') self._setBasisButton = JButton('Set Basis') self._hitOnceButton = JButton('Hit Once') self._autoScanButton = JButton('Auto Scan') self._clearLogButton = JButton('Clear Log') self._cancelButton = JButton('Cancel') self._levelSelection = JComboBox() self._levelSelection.addItem('1') self._levelSelection.addItem('2') self._levelSelection.addItem('3') self._hitOnceButton.addActionListener(listeners) self._autoScanButton.addActionListener(listeners) self._clearLogButton.addActionListener(listeners) self._setBasisButton.addActionListener(listeners) self._cancelButton.addActionListener(listeners) self._basisLabel.setPreferredSize(Dimension(100, 20)) # Create bottom pane for holding the buttons buttonPane = JPanel() buttonPane.setLayout(BorderLayout()) centerPane = JPanel() leftPane = JPanel() rightPane = JPanel() leftPane.add(self._basisLabel) centerPane.add(self._setBasisButton) centerPane.add(self._hitOnceButton) centerPane.add(self._autoScanButton) centerPane.add(self._cancelButton) centerPane.add(self._clearLogButton) rightPane.add(self._levelLabel) rightPane.add(self._levelSelection) buttonPane.add(centerPane, BorderLayout.CENTER) buttonPane.add(leftPane, BorderLayout.WEST) buttonPane.add(rightPane, BorderLayout.EAST) # Create and set the bottom panel that holds viewers and buttons utilPane = JPanel() utilPane.setLayout(BorderLayout()) utilPane.add(tabs, BorderLayout.CENTER) utilPane.add(buttonPane, BorderLayout.SOUTH) self._mainSplitpane.setLeftComponent(tableSplitpane) self._mainSplitpane.setRightComponent(utilPane) # Customize UI components callbacks.customizeUiComponent(self._mainSplitpane) callbacks.customizeUiComponent(dataTable) callbacks.customizeUiComponent(dataScrollPane) callbacks.customizeUiComponent(logTable) callbacks.customizeUiComponent(logScrollPane) callbacks.customizeUiComponent(tabs) callbacks.customizeUiComponent(buttonPane) callbacks.customizeUiComponent(utilPane) callbacks.customizeUiComponent(self._basisLabel) callbacks.customizeUiComponent(self._setBasisButton) callbacks.customizeUiComponent(self._hitOnceButton) callbacks.customizeUiComponent(self._autoScanButton) callbacks.customizeUiComponent(self._clearLogButton) callbacks.customizeUiComponent(self._levelSelection) callbacks.customizeUiComponent(self._cancelButton) # Add the custom tab to Burp's UI callbacks.addSuiteTab(self) # Register the context menu and message editor for new tabs callbacks.registerContextMenuFactory(self) # Register as a HTTP listener callbacks.registerHttpListener(self) return ''' ITab implementation ''' def getTabCaption(self): return 'InjectionScanner' def getUiComponent(self): return self._mainSplitpane ''' IContextMenuFactory implementation ''' def createMenuItems(self, invocation): menu = [] # Which part of the interface the user selects ctx = invocation.getInvocationContext() # Message viewer request will show menu item if selected by the user if ctx == 0 or ctx == 2: menu.append( swing.JMenuItem("Send to InjectionScanner", None, actionPerformed=lambda x, inv=invocation: self. sendToExtender(inv))) return menu if menu else None ''' IMessageEditorController Implementation ''' def getHttpService(self): return self._currentlyDisplayedItem.getHttpService() def getRequest(self): return self._currentlyDisplayedItem.getRequest() def getResponse(self): return self._currentlyDisplayedItem.getResponse() ''' IHttpListener implementation ''' def processHttpMessage(self, toolFlag, messageIsRequest, messageInfo): # Skip this function if the message is request if messageIsRequest: return # Lock the log entry in case race condition self._logLock.acquire() row = self._log.size() # Fetch request message requestBody = messageInfo.getRequest() requestInfo = self._helpers.analyzeResponse(requestBody) requestHeaders = requestInfo.getHeaders() if self._postGet == 'POST': requestData = self._helpers.bytesToString( requestBody[requestInfo.getBodyOffset():]) elif self._postGet == 'GET': for header in requestHeaders: if 'GET' in header: # If the request is GET, update the GET data requestUrl = re.sub('^GET\s+', '', header, re.IGNORECASE) requestUrl = re.sub('\sHTTP/1.1\S*', '', requestUrl, re.IGNORECASE) if '?' in requestUrl: requestData = re.sub('\S*\?', '', requestUrl, re.IGNORECASE) else: print('processHttpMessage: no parameter in GET url') else: print('processHttpMessage: _postGet not defined') self._logLock.release() return # Fetch the http type (GET/POST) httpType = requestHeaders[0].split(' ') # Fetch response message responseBody = messageInfo.getResponse() responseInfo = self._helpers.analyzeResponse(responseBody) responseHeaders = responseInfo.getHeaders() self._responseLength = '' # Fetch the content length self._responseLength = self.fetchContentLength(responseHeaders) # If the response message is auto-generated, ignore it. If not, add it into the log list if self._callbacks.getToolName(toolFlag) != 'Proxy': self._log.add( LogEntry(httpType[0], requestData, self._callbacks.saveBuffersToTempFiles(messageInfo), self._responseLength)) self._logTable.fireTableRowsInserted(row, row) self._logLock.release() ''' Fetch content length from the headers given ''' def fetchContentLength(self, fromHeaders): for header in fromHeaders: if re.search('^Content-Length', header, re.IGNORECASE) is not None: return re.sub('^Content-Length\:\s+', '', header, re.IGNORECASE) ''' When the user select 'Send to InjectionScanner', call this function ''' def sendToExtender(self, invocation): # Init/reset request data before sending to extender self.initRequestInfo() try: # Initialize basic information invMessage = invocation.getSelectedMessages() requestMessage = invMessage[0] requestInfo = self._helpers.analyzeRequest(requestMessage) self._requestBody = requestMessage.getRequest() # Set the _currentlyDisplayedItem so each time the data is sent to the extender self._currentlyDisplayedItem = self._callbacks.saveBuffersToTempFiles( requestMessage) # Fetch the request data bodyLen = len(self._helpers.bytesToString(self._requestBody)) if requestInfo.getBodyOffset() < bodyLen: self._requestData = self._helpers.bytesToString( self._requestBody[requestInfo.getBodyOffset():]) elif requestInfo.getBodyOffset() == bodyLen: self._requestData = '' else: print('sendToExtender: body length < body offset') # Fetch the headers and Http service requestHeaders = list(requestInfo.getHeaders()) self._httpService = requestMessage.getHttpService() # Initialize POST/GET identifier and User-Agent for header in requestHeaders: if re.search('^POST', header, re.IGNORECASE) is not None: self._postGet = 'POST' elif re.search('^GET', header, re.IGNORECASE) is not None: self._postGet = 'GET' # If the request is GET, initialize the url and GET data self._requestUrl = re.sub('^GET\s+', '', header, re.IGNORECASE) self._requestUrl = re.sub('\sHTTP/1.1\S*', '', self._requestUrl, re.IGNORECASE) if '?' in self._requestUrl: self._requestDataGet = re.sub('\S*\?', '', self._requestUrl, re.IGNORECASE) else: print('sendToExtender: no parameter in GET url') # If the request if POST, fetch the request data type by content type if self._postGet == 'POST' and re.search( '^Content-Type', header, re.IGNORECASE) is not None: contentType = re.sub('^Content-Type', '', header, re.IGNORECASE) if 'urlencoded' in contentType: self._dataType = 'urlencoded' elif 'json' in contentType: self._dataType = 'json' elif 'xml' in contentType or 'http' in conentType: self._dataType = 'xml' else: print( 'sendToExtender: _dataType is not supported, do not scan' ) # Initialze the User-Agent if it exists if re.search('^User-Agent', header, re.IGNORECASE) is not None: self._userAgent = re.sub('^User-Agent\:\s+', '', header, re.IGNORECASE) # If there's no content type in the header,fetch from data if self._postGet == 'POST' and self._dataType == '': if self._requestData != '': if self._requestData[ 0] == '{' and '}' in self._requestData and ':' in self._requestData: self._dataType = 'json' elif self._requestData[0] == '<' and self._requestData[ -1] == '>': self._dataType = 'xml' else: self._dataType = 'urlencoded' else: print( 'sendToExtender: _postGet is POST but _requestData is null' ) # Clear the table before adding elements self._dataTable.setRowCount(0) # Update request viewer self.updateRequestViewer() # Fill request data self.fillRequestData() except Exception as e: print(e) ''' Fill the data into the request table ''' def fillRequestData(self): # If _postGet is GET, also adds URL to the table if self._postGet == 'GET': dataList = self._requestDataGet.split('&') for data in dataList: if '=' in data: x = data.split('=', 1) self._dataDict[str(x[0])] = str(x[1]) self._dataTable.addRow([str(x[0]), str(x[1])]) self._dataLen += 1 self._dataTable.addRow(['URL', self._requestUrl]) self._UrlRow = self._dataLen if self._userAgent != '': self._dataTable.addRow(['User-Agent', self._userAgent]) elif self._postGet == 'POST': if self._dataType == 'urlencoded': dataList = self._requestData.split('&') for data in dataList: if '=' in data: x = data.split('=', 1) self._dataDict[str(x[0])] = str(x[1]) self._dataTable.addRow([str(x[0]), str(x[1])]) self._dataLen += 1 elif self._dataType == 'json': self._dataDict = json.loads(self._requestData) for key in self._dataDict: # Convert '"' to '\"' to be the same as that in the data value = str(self._dataDict[key]) if '\"' in value: value = value.replace('\"', '\\\"') self._dataDict[key] = value self._dataTable.addRow([str(key), self._dataDict[key]]) self._dataLen += 1 elif self._dataType == 'xml': # Use xml package to convert the xml string to dict # Note1: the xml dict will be in reverse order # Note2: the arrtibute will also be added into dict, need to be pop # Note3: special characters like \" will be considered as " xml.sax.parseString(self._requestData, self._xh) self._attr = re.sub('\>(\S*\s*)*', '', self._requestData[1:], re.IGNORECASE) self._dataDict = self._xh.getDict() self._dataDict.pop(self._attr) for key in self._dataDict: self._dataTable.addRow( [str(key), str(self._dataDict[key])]) self._dataLen += 1 else: print('fillRequestData: _dataType not defined') if self._userAgent != '': self._dataTable.addRow(['User-Agent', self._userAgent]) self._savedUserAgent = self._userAgent else: print('fillRequestData: _postGet not defined') ''' Receive & update the response after sending request to the server ''' def receiveResponse(self): # Init/reset response data before receiving response self.initResponseInfo() # Launch the http thread self._httpThread = Thread(target=self.makeRequest, args=( self._httpService, self._requestBody, )) self._httpThread.start() ''' Make Http request to a service ''' def makeRequest(self, httpService, requestBody): self._httpLock.acquire() # Disable the hit buttons before starting the thread self._hitOnceButton.setEnabled(False) self._autoScanButton.setEnabled(False) self._responseMessage = self._callbacks.makeHttpRequest( httpService, requestBody) # Enable the hit buttons self._hitOnceButton.setEnabled(True) self._autoScanButton.setEnabled(True) # Unblock the mutex self._httpLock.release() ''' updateRequestViewer ''' def updateRequestViewer(self): self._requestViewer.setMessage(self.getRequest(), True) ''' updateResponseViewer ''' def updateResponseViewer(self): self._responseViewer.setMessage(self.getResponse(), False) ''' Level 1 auto: only loop through the data, do not modify the 'submit' section ''' def autoScan1(self): # TODO: Add a 'cancel' button to stop when the user think it takes too long # TODO: Add XML support if self._postGet == 'GET': for i in range(0, self._dataLen): title = self._dataTable.getValueAt(i, 0) baseValue = self._dataDict[title] for value in self._simpleList: # TODO: update more value that should not be changed if 'submit' not in title.lower( ) and 'submit' not in self._dataDict[title].lower( ) and 'search' not in title.lower( ) and 'search' not in self._dataDict[title].lower(): # Update the table in case the loop interrupt in the middle # Note that the URL will be automatically updated due to this code, so no need to manually update the URL section self._dataTable.setValueAt(value, i, 1) # Send & request the HTTP request/response self.updateRequestViewer() self.receiveResponse() # Reset the table self._dataTable.setValueAt(baseValue, i, 1) if self._postGet == 'POST': if self._dataType == 'urlencoded' or self._dataType == 'json': for i in range(0, self._dataLen): title = self._dataTable.getValueAt(i, 0) baseValue = self._dataDict[title] if 'submit' in title.lower() or 'submit' in self._dataDict[ title].lower() or 'search' in title.lower( ) or 'search' in self._dataDict[title].lower(): continue for value in self._simpleList: self._dataTable.setValueAt(value, i, 1) self.updateRequestViewer() self.receiveResponse() # Reset the table self._dataTable.setValueAt(baseValue, i, 1) elif self._dataType == 'xml': for i in range(0, self._dataLen): title = self._dataTable.getValueAt(i, 0) baseValue = self._dataDict[title] for value in self._xmlList: # Update the table in case the loop interrupt in the middle self._dataTable.setValueAt(value, i, 1) # Send & request the HTTP request/response self.updateRequestViewer() self.receiveResponse() # Reset the table self._dataTable.setValueAt(baseValue, i, 1) ''' Level 2 auto: loop through the data as well as the user agent (if exist) ''' def autoScan2(self): # If the User-Agent does not exist, only performs level 1 auto if self._userAgent != '': baseUserAgent = self._userAgent baseExpression = 'User-Agent: ' + baseUserAgent for value in self._simpleList: oldExpression = 'User-Agent: ' + self._userAgent newExpression = 'User-Agent: ' + value # Update the values accordingly requestBodyString = self._helpers.bytesToString( self._requestBody) self._requestBody = requestBodyString.replace( oldExpression, newExpression) self._userAgent = value self.updateRequestViewer() self.receiveResponse() # Reset the value back to original after each loop requestBodyString = self._helpers.bytesToString(self._requestBody) self._requestBody = requestBodyString.replace( newExpression, baseExpression) self._savedUserAgent = baseUserAgent self.updateRequestViewer() # Perform level 1 scan also self.autoScan1() ''' Level 3 auto: Alpha: use the timer to perform blind insertion ''' # TODO: 目前只支持GET/urlencoded,后续添加更多支持 def autoScan3(self): self._timeReach = False timer = Timer(5, self.timeReach) # Modify the first element to perform blind injection title = self._dataTable.getValueAt(i, 0) oldExpression = title + '=' + self._dataDict[title] newExpression = title + '=' + '1\' and if(1=0,1, sleep(10)) --+' if self._postGet == 'GET': # Update the values accordingly requestBodyString = self._helpers.bytesToString(self._requestBody) self._requestBody = requestBodyString.replace( oldExpression, newExpression) self._requestDataGet = self._requestDataGet.replace( oldExpression, newExpression) self._requestUrl = self._requestUrl.replace( oldExpression, newExpression) self._dataDict[title] = '1\' and if(1=0,1, sleep(10)) --+' self._requestModel.setValueAt('1\' and if(1=0,1, sleep(10)) --+', 0, 1) elif self._postGet == 'POST': if self._dataType == 'urlencoded': # Update the values accordingly requestBodyString = self._helpers.bytesToString( self._requestBody) self._requestBody = requestBodyString.replace( oldExpression, newExpression) self._requestData = self._requestData.replace( oldExpression, newExpression) self._dataDict[title] = '1\' and if(1=0,1, sleep(10)) --+' self._requestModel.setValueAt( '1\' and if(1=0,1, sleep(10)) --+', 0, 1) else: print('autoScan3: _dataType not supported') else: print('autoScan3: _postGet not defined') timer.start() self.updateRequestViewer() self.receiveResponse() # Print the result if self._timeReach: print('Delay scan succeed') else: print('Delay scan failed') # Cancel the timer timer.cancel() def timeReach(self): self._timeReach = True ''' Fetch the 'abnormal' payloads that shows very different response length from the normal ones ''' def getAbnormal(self, basis, coefficient): # If the basis is not set, do nothing abnormList = ArrayList() if basis == 0: return None # Fetch the abnormals from the log list for log in self._log: if float(log._responseLen) / float(basis) < coefficient or float( basis) / float(log._responseLen) < coefficient: abnormList.append(log._payload) return abnormList ''' Turn a simple dict of key/value pairs into XML ''' def dictToXml(self, tag, d): elem = Element(tag) for key, val in d.items(): child = Element(key) child.text = str(val) # Add element in reverse order so that the result is correct elem.insert(0, child) return elem ''' initRequestInfo ''' def initRequestInfo(self): self._postGet = '' self._userAgent = '' self._requestUrl = '' self._requestBody = '' self._requestData = '' self._requestDataGet = '' self._httpService = None self._dataDict = {} self._dataType = '' self._dataLen = 0 self._attr = '' self._contentLength = 0 self._currentlyDisplayedItem = None ''' initResponseInfo ''' def initResponseInfo(self): self._responseBody = None self._responseMessage = None self._responseLength = '' ''' printRequest ''' def printRequest(self): print('----------------') print(self._postGet) print('----------------') print(self._userAgent) print('----------------') print(self._requestUrl) print('----------------') print(self._requestBody) print('----------------') print(self._requestData) print('----------------') print(self._requestDataGet) print('----------------') print(self._httpService) print('----------------') print(self._dataDict) print('----------------') print(self._dataLen) print('----------------') print(self._attr) print('----------------') ''' printResponse ''' def printResponse(self): print('----------------') print(self._responseBody) print('----------------') print(self._responseMessage) print('----------------') print(self._responseLength) print('----------------')
class SourceCellRenderer(TreeCellRenderer): def __init__(self,tree,mapContext): self.tree = tree self.mapContext = mapContext ## Group self.lblFolder = JLabel() self.lblFolder.setBackground(Color(222,227,233)) #.BLUE.brighter()) self.lblFolder.setOpaque(True) self.lblFolder.setText("plddddddddddddddddddddddddddddddddddddddddddddddddddddddd") ### Folder self.pnlFolder = JPanel() self.pnlFolder.setOpaque(False) self.pnlFolder.setLayout(FlowLayout(FlowLayout.LEFT)) self.lblGroup = JLabel() #self.lblGroup.setBackground(Color(222,227,233)) #.BLUE.brighter()) #self.lblGroup.setOpaque(True) self.lblGroup.setText("plddddddddddddddddddddddddddddddddddddddddddddddddddddddd") self.lblGroupPreferredSize = self.lblGroup.getPreferredSize() self.lblGroupIcon = JLabel() self.pnlFolder.add(self.lblGroupIcon) self.pnlFolder.add(self.lblGroup) #self.lblGroup.setBorder( # BorderFactory.createLineBorder(Color(222,227,233).darker(),1) #) #self.lblGroupPreferredSize.setSize(30,200)#self.lblGroupPreferredSize.getHeight()+4, self.lblGroupPreferredSize.getWidth()) ### LAYER self.pnlLayer = JPanel() self.pnlLayer.setOpaque(False) #self.pnlLayer.setBorder(EmptyBorder(2,2,2,2)) self.pnlLayer.setLayout(FlowLayout(FlowLayout.LEFT)) self.chkLayerVisibility = JCheckBox() self.chkLayerVisibility.setOpaque(False) self.pnlLayer.add(self.chkLayerVisibility) self.lblLayerIcon = JLabel() self.lblLayerName = JLabel() self.pnlLayer.add(self.lblLayerIcon) self.pnlLayer.add(self.lblLayerName) #self.tree.setRowHeight(int(self.pnlLayer.getPreferredSize().getHeight())) #+2 self.tree.setRowHeight(int(self.pnlFolder.getPreferredSize().getHeight())) self.lblUnknown = JLabel() def getTreeCellRendererComponent(self, tree, value, selected, expanded, leaf, row, hasFocus): uo = value.getUserObject() if isinstance(uo, DataFolder): #self.lblFolder.setText(uo.getName()) text = "[" + str(value.getChildCount()) +"] " + uo.getName() self.lblFolder.setText(text) self.lblFolder.setPreferredSize(self.lblGroupPreferredSize) if uo.getIcon()!=None: self.lblGroupIcon.setIcon(uo.getIcon()) else: self.lblGroupIcon.setIcon(getIconByName("librarybrowser-folder")) #icon-folder-open")) return self.lblFolder if isinstance(uo, DataGroup): self.lblGroup.setText(uo.getName()) self.lblGroup.setPreferredSize(self.lblGroupPreferredSize) if uo.getIcon()!=None: self.lblGroupIcon.setIcon(uo.getIcon()) else: #import pdb #pdb.set_trace() self.lblGroupIcon.setIcon(getIconByName("librarybrowser-folder")) #icon-folder-open")) return self.pnlFolder if isinstance(uo, DataLayer): layer = uo.getLayer() self.lblLayerName.setText(layer.getName()) self.lblLayerIcon.setIcon(getIconFromLayer(layer)) self.chkLayerVisibility.setSelected(layer.isVisible()) if layer.isWithinScale(self.mapContext.getScaleView()): # and layer.isVisible(): self.chkLayerVisibility.setEnabled(True) else: self.chkLayerVisibility.setEnabled(False) self.lblLayerName.setForeground(Color.BLACK) font = self.lblLayerName.getFont() self.lblLayerName.setForeground(Color.BLACK) if layer.isEditing(): self.lblLayerName.setForeground(Color.RED) if layer.isActive() and font.isBold(): pass elif layer.isActive() and not font.isBold(): newfont = font.deriveFont(Font.BOLD) self.lblLayerName.setFont(newfont) else: newfont = font.deriveFont(Font.PLAIN) self.lblLayerName.setFont(newfont) #self.pnlLayer.repaint() return self.pnlLayer self.lblUnknown.setText("") self.lblUnknown.setPreferredSize(Dimension(0,0)) return self.lblUnknown
def reloadComponent(game,dialog,node): c = None text = node.getAttribute("text") if node.hasAttribute("text") else "" align = int(node.getAttribute("align")) if node.hasAttribute("align") else 0 #Components if node.nodeName=="jpanel": reloadJPanel(game,dialog,node) elif node.nodeName=="jlabel": c = JLabel(text,align) elif node.nodeName=="settingspanel": c = SettingsPanel(game) for g in node.childNodes: if g.nodeName=="group": c.addGroup(int(g.getAttribute("id")),g.getAttribute("label")) for h in g.childNodes: if h.nodeName=="heading": c.addHeading(int(g.getAttribute("id")),h.getAttribute("label")) for s in h.childNodes: if s.nodeName=="setting": #<setting id="1" name="DISPLAY_REAL_WORLD_TIME" type="checkbox" label="Show Real-World Time"></setting> if s.getAttribute("items")!="": c.addSettingWithItems(int(g.getAttribute("id")),int(s.getAttribute("id")),s.getAttribute("label"),s.getAttribute("type"),s.getAttribute("items").split(",")) else: c.addSetting(int(g.getAttribute("id")),int(s.getAttribute("id")),s.getAttribute("label"),s.getAttribute("type")) c.finalizeSettingsPanel() dialog.registerSettingsPanel(int(node.getAttribute("id")),c) elif node.nodeName=="logspanel": c = LogsPanel(game) for g in node.childNodes: if g.nodeName=="group": c.addLog(int(g.getAttribute("id")),g.getAttribute("label")) c.finalizeLogsPanel() dialog.registerLogsPanel(int(node.getAttribute("id")),c) elif node.nodeName=="jbutton": reloadJButton(game,dialog,node,text,align) elif node.nodeName=="nglcanvas": c = NGLCanvas(game,int(getCascadingAttribute(game,node,"width")),int(getCascadingAttribute(game,node,"height"))) dialog.registerCanvas(int(node.getAttribute("id")),c) #Layout if node.parentNode.getAttribute("layout")=="absolute": c.setBounds(getBounds(game,node)) elif node.parentNode.getAttribute("layout")=="box-y": c.setAlignmentX(Component.CENTER_ALIGNMENT); if node.hasAttribute("width") and node.hasAttribute("height"): c.setPreferredSize(Dimension(int(getCascadingAttribute(game,node,"width")),int(getCascadingAttribute(game,node,"height")))) if node.hasAttribute("minWidth") and node.hasAttribute("minHeight"): c.setMinimumSize(Dimension(int(node.getAttribute("minWidth")),int(node.getAttribute("minHeight")))) if node.hasAttribute("maxWidth") and node.hasAttribute("maxHeight"): c.setMaximumSize(Dimension(int(node.getAttribute("maxWidth")),int(node.getAttribute("maxHeight")))) elif node.parentNode.getAttribute("layout")=="box-x": c.setAlignmentY(Component.CENTER_ALIGNMENT); if node.hasAttribute("width") and node.hasAttribute("height"): c.setPreferredSize(Dimension(int(getCascadingAttribute(game,node,"width")),int(getCascadingAttribute(game,node,"height")))) if node.hasAttribute("minWidth") and node.hasAttribute("minHeight"): c.setMinimumSize(Dimension(int(node.getAttribute("minWidth")),int(node.getAttribute("minHeight")))) if node.hasAttribute("maxWidth") and node.hasAttribute("maxHeight"): c.setMaximumSize(Dimension(int(node.getAttribute("maxWidth")),int(node.getAttribute("maxHeight")))) if node.nodeName!="nglcanvas" and node.nodeName!="jpanel" and node.nodeName!="settingspanel": addListeners(game,c,node) return c;
class BeautifierPanel(JPanel): def __init__(self): super(BeautifierPanel, self).__init__() self.setLayout(BorderLayout()) self.beautifyTextArea = JTextArea(5, 10) self.beautifyTextArea.setLineWrap(True) self.beautifyTextArea.setDocument(self.CustomUndoPlainDocument()) # The undo doesn't work well before replace text. Below is rough fix, so not need to know how undo work for now self.beautifyTextArea.setText(" ") self.beautifyTextArea.setText("") self.undoManager = UndoManager() self.beautifyTextArea.getDocument().addUndoableEditListener( self.undoManager) self.beautifyTextArea.getDocument().addDocumentListener( self.BeautifyDocumentListener(self)) beautifyTextWrapper = JPanel(BorderLayout()) beautifyScrollPane = JScrollPane(self.beautifyTextArea) beautifyTextWrapper.add(beautifyScrollPane, BorderLayout.CENTER) self.add(beautifyTextWrapper, BorderLayout.CENTER) self.beautifyButton = JButton("Beautify") self.beautifyButton.addActionListener(self.beautifyListener) self.undoButton = JButton("Undo") self.undoButton.addActionListener(self.undoListener) formatLabel = JLabel("Format:") self.formatsComboBox = JComboBox() for f in supportedFormats: self.formatsComboBox.addItem(f) self.statusLabel = JLabel("Status: Ready") preferredDimension = self.statusLabel.getPreferredSize() self.statusLabel.setPreferredSize( Dimension(preferredDimension.width + 20, preferredDimension.height)) self.sizeLabel = JLabel("0 B") preferredDimension = self.sizeLabel.getPreferredSize() self.sizeLabel.setPreferredSize( Dimension(preferredDimension.width + 64, preferredDimension.height)) self.sizeLabel.setHorizontalAlignment(SwingConstants.RIGHT) buttonsPanel = JPanel(FlowLayout()) buttonsPanel.add(formatLabel) buttonsPanel.add(self.formatsComboBox) buttonsPanel.add(Box.createHorizontalStrut(10)) buttonsPanel.add(self.beautifyButton) buttonsPanel.add(self.undoButton) bottomPanel = JPanel(BorderLayout()) bottomPanel.add(self.statusLabel, BorderLayout.WEST) bottomPanel.add(buttonsPanel, BorderLayout.CENTER) bottomPanel.add(self.sizeLabel, BorderLayout.EAST) self.add(bottomPanel, BorderLayout.SOUTH) self.currentBeautifyThread = None class CustomUndoPlainDocument(PlainDocument): # Code from: https://stackoverflow.com/questions/24433089/jtextarea-settext-undomanager compoundEdit = CompoundEdit() def fireUndoableEditUpdate(self, e): if self.compoundEdit == None: super(BeautifierPanel.CustomUndoPlainDocument, self).fireUndoableEditUpdate(e) else: self.compoundEdit.addEdit(e.getEdit()) def replace(self, offset, length, text, attrs): if length == 0: super(BeautifierPanel.CustomUndoPlainDocument, self).replace(offset, length, text, attrs) else: self.compoundEdit = CompoundEdit() super(BeautifierPanel.CustomUndoPlainDocument, self).fireUndoableEditUpdate( UndoableEditEvent(self, self.compoundEdit)) super(BeautifierPanel.CustomUndoPlainDocument, self).replace(offset, length, text, attrs) self.compoundEdit.end() self.compoundEdit = None def setText(self, text): self.beautifyTextArea.setText(text) def setRunningState(self): self.beautifyButton.setText("Cancel") self.undoButton.setEnabled(False) self.statusLabel.setText("Status: Running") def setReadyState(self): self.beautifyButton.setText("Beautify") self.undoButton.setEnabled(True) self.statusLabel.setText("Status: Ready") class BeautifyDocumentListener(DocumentListener): def __init__(self, beautifierPanel): super(BeautifierPanel.BeautifyDocumentListener, self).__init__() self.beautifierPanel = beautifierPanel def removeUpdate(self, e): self.updateSizeLabel() def insertUpdate(self, e): self.updateSizeLabel() def changedUpdate(self, e): pass def updateSizeLabel(self): length = len(self.beautifierPanel.beautifyTextArea.getText()) if length >= 1024: length = "%.2f KB" % (length / 1024.0) else: length = "%d B" % length self.beautifierPanel.sizeLabel.setText(length) def beautifyListener(self, e): selectedFormat = self.formatsComboBox.getSelectedItem() data = self.beautifyTextArea.getText( ) # variable "data" is "unicode" type if self.currentBeautifyThread and self.currentBeautifyThread.isAlive(): # TODO Need a graceful way to shutdown running beautify thread. self.currentBeautifyThread.callback = None self.currentBeautifyThread = None self.setReadyState() else: self.currentBeautifyThread = None self.setRunningState() def beautifyCallback(result): self.beautifyTextArea.setText(result) self.setReadyState() self.currentBeautifyThread = BeautifyThread( data, selectedFormat, beautifyCallback) self.currentBeautifyThread.start() def undoListener(self, e): if self.undoManager.canUndo(): self.undoManager.undo()
def registerExtenderCallbacks(self, callbacks): self._callbacks = callbacks self._helpers = callbacks.getHelpers() callbacks.setExtensionName("Module Importer") self.out = callbacks.getStdout() self.tab = JPanel(GridBagLayout()) self.tableData = [] colNames = ('Enabled', 'Module') self.dataModel = MyTableModel(self.tableData, colNames) self.table = JTable(self.dataModel) self.tablecont = JScrollPane(self.table) c = GridBagConstraints() c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 0 c.gridy = 4 c.gridheight = 6 c.gridwidth = 6 c.weightx = 0.6 c.weighty = 0.5 self.tab.add(self.tablecont, c) self.fc = JFileChooser() self.fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY) label_for_openDirectory = JLabel("Module Importer") c = GridBagConstraints() c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 0 c.gridy = 0 self.tab.add(label_for_openDirectory, c) label_plugin_desc = JLabel( "This module makes your development of Burp Suite Plugin easier.") label_plugin_desc.setPreferredSize(Dimension(400, 50)) c = GridBagConstraints() c.gridx = 0 c.gridy = 1 self.tab.add(label_plugin_desc, c) label_for_openDirectory = JLabel("Module Path:") c = GridBagConstraints() c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 0 c.gridy = 2 self.tab.add(label_for_openDirectory, c) c = GridBagConstraints() c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 0 c.gridy = 3 self.input_id = JTextField(40) self.input_id.setEditable(java.lang.Boolean.FALSE) self.tab.add(self.input_id, c) c = GridBagConstraints() c.anchor = GridBagConstraints.FIRST_LINE_START c.gridx = 1 c.gridy = 3 self.openButton = JButton("Open Directory", actionPerformed=self.openDialog) self.tab.add(self.openButton, c) if M_PATH: self.set_fixed_module_path() #callbacks.customizeUiComponent(self.tab) #callbacks.customizeUiComponent(self.table) #callbacks.customizeUiComponent(self.tablecont) callbacks.addSuiteTab(self) callbacks.registerProxyListener(self) return
class SelectionCellRenderer(TreeCellRenderer): def __init__(self, tree, mapContext): self.tree = tree self.mapContext = mapContext self.lblGroup = JLabel() self.lblGroup.setBackground(Color(222, 227, 233)) #.BLUE.brighter()) self.lblGroup.setOpaque(True) self.lblGroup.setText( "plddddddddddddddddddddddddddddddddddddddddddddddddddddddd") self.lblGroupPreferredSize = self.lblGroup.getPreferredSize() #h = self.lblGroupPreferredSize.getHeight() #w = self.lblGroupPreferredSize.getWidth() #self.lblGroupPreferredSize.setSize(h, w) self.pnlLayer = JPanel() self.pnlLayer.setOpaque(False) self.pnlLayer.setLayout(FlowLayout(FlowLayout.LEFT)) self.lblClean = JLabel() self.chkLayerVisibility = JCheckBox() self.chkLayerVisibility.setOpaque(False) self.lblLayerName = JLabel() self.lblLayerIcon = JLabel() self.lblFeatureSelecteds = JLabel() self.pnlLayer.add(self.chkLayerVisibility) self.pnlLayer.add(self.lblClean) self.pnlLayer.add(self.lblFeatureSelecteds) self.pnlLayer.add(self.lblLayerIcon) self.pnlLayer.add(self.lblLayerName) self.tree.setRowHeight( int(self.pnlLayer.getPreferredSize().getHeight()) - 3) self.lblUnknown = JLabel() ## Feature self.lblFeatureIcon = JLabel() self.lblFeatureName = JLabel() i18n = ToolsLocator.getI18nManager() self.lblFeatureName.setText(i18n.getTranslation("_Feature")) self.pnlFeature = JPanel() self.pnlFeature.setOpaque(False) self.pnlFeature.setLayout(FlowLayout(FlowLayout.LEFT)) self.pnlFeature.add(self.lblFeatureIcon) self.pnlFeature.add(self.lblFeatureName) def getTreeCellRendererComponent(self, tree, value, selected, expanded, leaf, row, hasFocus): uo = value.getUserObject() if isinstance(uo, DataGroup): text = "[" + str(value.getChildCount()) + "] " + uo.getName() self.lblGroup.setText(text) self.lblGroup.setPreferredSize(self.lblGroupPreferredSize) return self.lblGroup if isinstance(uo, DataLayer): layer = uo.getLayer() self.lblLayerName.setText(uo.getName()) self.lblLayerIcon.setIcon(getIconFromLayer(layer)) if layer.isVisible(): self.lblLayerName.setEnabled(True) else: self.lblLayerName.setEnabled(False) self.lblClean.setIcon(getIconByName("edit-clear")) self.chkLayerVisibility.setSelected(layer.isVisible()) if layer.isWithinScale( self.mapContext.getScaleView()): # and layer.isVisible(): self.chkLayerVisibility.setEnabled(True) else: self.chkLayerVisibility.setEnabled(False) if layer.getDataStore() != None and layer.getDataStore( ).getSelection() != None and layer.getDataStore().getSelection( ).getSize() != 0: # and layer.isVisible(): self.lblClean.setEnabled(True) self.lblFeatureSelecteds.setText( str(layer.getDataStore().getSelection().getSize())) self.lblFeatureSelecteds.setEnabled(True) else: self.lblClean.setEnabled(False) self.lblFeatureSelecteds.setText("0") self.lblFeatureSelecteds.setEnabled(False) font = self.lblLayerName.getFont() self.lblLayerName.setForeground(Color.BLACK) if layer.isEditing(): self.lblLayerName.setForeground(Color.RED) #if layer.isActive(): if layer.isActive(): # and not font.isBold(): newfont = font.deriveFont(Font.BOLD) self.lblLayerName.setFont(newfont) else: newfont = font.deriveFont(Font.PLAIN) self.lblLayerName.setFont(newfont) return self.pnlLayer if isinstance(uo, FeatureDataLayerNode): self.lblFeatureName.setText(uo.getFeature().toString()) self.lblFeatureIcon.setIcon(getIconByName("edit-clear")) return self.pnlFeature self.lblUnknown.setText("") self.lblUnknown.setPreferredSize(Dimension(0, 0)) return self.lblUnknown
def build_gui(self): """Construct GUI elements.""" Mpanel = JPanel() # Mpanel.setLayout(GridLayout(0, 3)) Mpanel.setLayout(BoxLayout(Mpanel, BoxLayout.X_AXIS)) panel = JPanel() panel.setLayout(None) Mpanel.add(Box.createVerticalGlue()) Mpanel.add(panel) Mpanel.add(Box.createVerticalGlue()) img = os.path.abspath("gat_logo_sticky.png") logo = JLabel(ImageIcon(img)) logo.setBounds(150, 40, 165, 49) save_btn = JButton('Salvar', actionPerformed=self.save_config) save_btn.setBounds(100, 240, 75, 30) save_btn.setPreferredSize(Dimension(75, 30)) limpar_btn = JButton('Limpar ID Projeto', actionPerformed=self.clsProjectId) limpar_btn.setBounds(250, 240, 150, 30) limpar_btn.setPreferredSize(Dimension(150, 30)) label_h = JLabel('API Url:') label_h.setHorizontalAlignment(SwingConstants.RIGHT) label_h.setBounds(0, 120, 95, 30) label_h.setPreferredSize(Dimension(100, 30)) self.host_api = JTextField(50) self.host_api.setBounds(100, 120, 300, 30) self.host_api.setPreferredSize(Dimension(250, 30)) label_a = JLabel('API Token:') label_a.setHorizontalAlignment(SwingConstants.RIGHT) label_a.setBounds(0, 160, 95, 30) label_a.setPreferredSize(Dimension(100, 30)) self.api_token = JTextField(50) self.api_token.setBounds(100, 160, 300, 30) self.api_token.setPreferredSize(Dimension(250, 30)) label_p = JLabel('Project ID:') label_p.setHorizontalAlignment(SwingConstants.RIGHT) label_p.setBounds(0, 200, 95, 30) label_p.setPreferredSize(Dimension(100, 30)) self.project_id = JTextField(50) self.project_id.setForeground(Color.orange) self.project_id.setBackground(Color.gray) self.project_id.setBounds(100, 200, 300, 30) self.project_id.setPreferredSize(Dimension(250, 30)) self.project_id.editable = False panel.add(logo) panel.add(label_h) panel.add(self.host_api) panel.add(label_a) panel.add(self.api_token) panel.add(label_p) panel.add(self.project_id) panel.add(limpar_btn) panel.add(save_btn) return Mpanel
class JBrukerSubmit: colHeads = ('block/sample #', 'Holder', 'Name', 'Experiment', 'Solvent', 'Group', 'Member', 'Sample Name') if platform.node() == 'DM-CHEM-200': basedir = r"W:\downloads\Eric\jython" elif platform.node() == 'ERIC-PC': basedir = r"C:\Users\ERIC\Dropbox\projects\programming\2020\python\autoNMRinput" else: # running from Bruker spectrometers basedir = "/data/downloads/Eric" def listSubmit(self, event): """Submit highlighted to csv file to automation folder of spectrometer """ # Ask for starting carousel position and submit experimets to topspin # obtain file name of CSV file selected = self.list.selectedIndex csvName = self.data[selected] # if no selected file and table is empty just return if self.label.text == "Selected File": return # Create check dialog before submitting data to automation self.dataTableModel.dataVector # submitString = "submit " + csvName + " starting at carousel position " + self.carouselStartingPosition.text submitString = "submit " + csvName + " starting at carousel position " + str( (self.dataTableModel.dataVector)[0][1]) result = JOptionPane.showConfirmDialog(self.frame, submitString) # if submission confirmed if result == 0: # submit csv file to automation ret = readcsv243A.submitNMRexpts([ self.dataTableModel.dataVector, csvName, self.carouselStartingPosition.text ]) # if successful or not update status string if ret == 0: self.statusLabel.text = "File " + csvName + " Submitted to TOPSPIN Starting at Carousel Position " + str( (self.dataTableModel.dataVector)[0][1]) self.panelStatusLabel.setBackground(Color.GREEN) elif ret == 1: self.statusLabel.text = "Carousel Position not a number" self.panelStatusLabel.setBackground(Color.RED) elif ret == 2: self.statusLabel.text = "Incompatible experiment chosen for spectrometer" self.panelStatusLabel.setBackground(Color.RED) elif ret == 3: self.statusLabel.text = "A holder starting position is not between 1 and 60 inclusive" self.panelStatusLabel.setBackground(Color.RED) elif ret == 4: self.statusLabel.text = "Too many samples for starting position chosen" self.panelStatusLabel.setBackground(Color.RED) # if an error occured display error message also in a warning dialog too. if ret in [1, 2, 3, 4]: JOptionPane.showMessageDialog(self.frame, self.statusLabel.text) def listSelect(self, event): """When a new csv file is selected from the list read in the file and display its contents in the table. Unordered csv files will be ordered based on the block/sample number. A holder column will be added to the CSV data based on the carousel starting position. """ # Process the events from the list box and update the label # get the index from the list and then the filename selected = self.list.selectedIndex if selected >= 0: # update file label and set background colour to normal csvName = self.data[selected] self.label.text = csvName self.panelLabel.setBackground(self.standardBackgroundColor) # reset status label self.statusLabel.text = "Status" self.panelStatusLabel.setBackground(self.standardBackgroundColor) # # update table by reading in csv file # read in csv file and store as a list of dictionaries # one dictionary for each line fn = csvName self.expt_list = [] f = open(os.path.join(JBrukerSubmit.basedir, fn), 'r') reader = csv.DictReader(f) for row in reader: self.expt_list.append(row) f.close() # get carousel starting position, if the value cannot be converted # to an integer reset it to 1 and reset the GUI to 1 try: self.cnumber = int(self.carouselStartingPosition.text) except: self.cnumber = 1 self.self.carouselStartingPosition.text = "1" # get the csv data into a list of lists form ready for displaying self.tableData = returnJTableData(self.expt_list, self.cnumber) # display csv table in table view colNames = JBrukerSubmit.colHeads # transfer the data over to the table model self.dataTableModel.setDataVector(self.tableData, colNames) # display the table in the GUI self.scrollPaneTable.getViewport().setView((self.table)) # check to see if experiments will run on the spectometer ok, pulseSequence = checkExperimentsWillRun(self.expt_list) if not ok: # display warning dialog warningText = pulseSequence + " cannot be run on this spectrometer" JOptionPane.showMessageDialog(self.frame, warningText) def returnCSVlist(self, hiddenFiles): """ read in csv files ommitting any that are created after auto submission and return as list of strings. Miss out any that have been hidden""" csvlist = [ f for f in os.listdir(JBrukerSubmit.basedir) if (f.endswith(".csv")) and (f[-6] not in ['A', 'B', 'N']) ] csvlist = [f for f in csvlist if f not in self.hiddenFiles] return csvlist def listUpdate(self, event): """ when update button clicked renew csv list """ self.data = self.returnCSVlist(self.hiddenFiles) self.list.setListData(self.data) def checkCarouselNumber(self, event): """ check that carousel field is an integer change background to white if okay, red if not.""" self.cnumber = self.carouselStartingPosition.text try: self.cnumber = int(self.cnumber) self.carouselStartingPosition.background = Color.WHITE self.listSelect(event) except: self.carouselStartingPosition.background = Color.RED def tableMouseClicked(self, event): """Prior to editing the user will click the holder number cell more often than not. This function saves the cell row and column and the value in the cell prior to editing.""" tble = event.getSource() self.rw = tble.getSelectedRow() self.cl = tble.getSelectedColumn() self.oldHolderValue = tble.getValueAt(self.rw, self.cl) # print "table mouse clicked", self.rw, self.cl def tableChangedCB(self, event): """Function is called when a cell is being edited. After the user presses return the data is updated. Should only work if Holder column is being edited""" print "Table Changed" tble = event.getSource() if (event.keyChar == "\n") and (self.cl != 1): tble.setValueAt(self.oldHolderValue, self.rw, self.cl) elif (event.keyChar == "\n") and (self.cl == 1): print "RETURN" vlue = tble.getValueAt(self.rw, self.cl) print "row", self.rw, "col", self.cl, "value", vlue # # check to see if new holder number is used by another sample # get block number of sample changed blckNumber = tble.getValueAt(self.rw, 0) # # get values in table holderAlreadyOccupied = False tableValues = self.dataTableModel.dataVector for i, rw in enumerate(tableValues): print i if (int(rw[1]) == int(vlue)) and (int(blckNumber) != int(rw[0])): tble.setValueAt(int(self.oldHolderValue), self.rw, 1) holderAlreadyOccupied = True warningText = "Holder " + str( vlue) + " already used for sample " + str(rw[0]) JOptionPane.showMessageDialog(self.frame, warningText) break # # check to see if any other rows with same sample number need to be updated if not holderAlreadyOccupied: for i, rw in enumerate(tableValues): if int(blckNumber) == int(rw[0]): tble.setValueAt(int(vlue), i, 1) # def tableKeyPressedCB(self, event): # print "tableKeyPressedCB" # tble = event.getSource() # if event.keyChar == "\n": # print "RETURN" # vlue = tble.getValueAt(self.rw, self.cl) # print "row", self.rw, "col", self.cl, "value", vlue # elif (event.keyChar).isdigit(): # print "event.keyChar", event.keyChar # self.rw = tble.getSelectedRow() # self.cl = tble.getSelectedColumn() def listShowAllFiles(self, event): fp = open("hiddenFiles.txt", 'w') fp.write('zzz\n') fp.close() self.hiddenFiles = ['zzz'] self.listUpdate(event) def listHideFile(self, event): # find highlighted csv file name selected = self.list.selectedIndex csvName = self.data[selected] # add csv file name to hidden csv files list self.hiddenFiles.append(csvName) # update label above table view self.label.text = "Selected File" self.panelLabel.setBackground(self.standardBackgroundColor) # display csv table in table view # set table to blanks self.tableData = [] for i in range(18): self.tableData.append([ "", ] * len(JBrukerSubmit.colHeads)) self.dataTableModel.setDataVector(self.tableData, JBrukerSubmit.colHeads) self.listUpdate(event) # save hiddenFiles file fp = open("hiddenFiles.txt", 'w') for f in self.hiddenFiles: fp.write(f + '\n') fp.close() def __init__(self): self.rw = 0 # table row self.cl = 0 # table column # load hidden files list self.hiddenFiles = ["zzz"] if os.path.exists("hiddenFiles.txt"): fp = open("hiddenFiles.txt", "r") self.hiddenFiles = fp.readlines() fp.close() self.hiddenFiles = [f.strip() for f in self.hiddenFiles] print self.hiddenFiles # These lines setup the basic frame, size and layout # the setDefaultCloseOperation so that only the window closes and not TOPSPIN self.frame = JFrame("Submit NMR Experimets") self.frame.setSize(1200, 440) self.frame.setLayout(BorderLayout()) self.frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) # set up the list and the contents of the list # the python tuple get converted to a Java vector self.data = self.returnCSVlist(self.hiddenFiles) self.list = JList(self.data, valueChanged=self.listSelect) self.spane = JScrollPane() self.spane.setPreferredSize(Dimension(145, 150)) self.spane.getViewport().setView((self.list)) panel = JPanel() panel.add(self.spane) # define buttons bpanel = JPanel() btnS = JButton('Submit File', actionPerformed=self.listSubmit) btnU = JButton('Update List', actionPerformed=self.listUpdate) btnHideFile = JButton('Hide File', actionPerformed=self.listHideFile) btnShowAllFiles = JButton('Show All Files', actionPerformed=self.listShowAllFiles) # label displaying CSV file selected self.label = JLabel('Selected File', JLabel.CENTER) # label to display warnings and confirm expriments submitted self.statusLabel = JLabel('Status', JLabel.CENTER) # Create table to display csv file self.tableData = [] for r in range(18): self.tableData.append([ "", ] * len(JBrukerSubmit.colHeads)) colNames = JBrukerSubmit.colHeads self.dataTableModel = DefaultTableModel(self.tableData, colNames) self.table = JTable(self.dataTableModel, keyTyped=self.tableChangedCB, mouseClicked=self.tableMouseClicked) # set all columns to uneditable except Holder column # print dir(self.table) # self.table.getColumn(0).setEditable(False) # self.table.getColumn(2).setEditable(False) # self.table.getColumn(3).setEditable(False) # self.table.getColumn(4).setEditable(False) # self.table.getColumn(5).setEditable(False) # self.table.getColumn(6).setEditable(False) # self.table = JTable(self.dataTableModel, # keyPressed=self.tableKeyPressedCB) self.scrollPaneTable = JScrollPane() self.scrollPaneTable.setPreferredSize(Dimension(900, 300)) self.scrollPaneTable.getViewport().setView((self.table)) panelTable = JPanel() panelTable.add(self.scrollPaneTable) # create text field to get carousel starting position self.carouselLabel = JLabel("Carousel Position", JLabel.CENTER) self.carouselStartingPosition = JTextField( '1', 13, keyPressed=self.checkCarouselNumber) # add widgets to do with manupulating csv list in FlowLayout Mode panelList = JPanel() panelList.setLayout(FlowLayout()) panelList.setPreferredSize(Dimension(170, 200)) # set preferred size of buttons btnU.setPreferredSize(Dimension(140, 20)) btnS.setPreferredSize(Dimension(140, 20)) btnHideFile.setPreferredSize(Dimension(140, 20)) btnShowAllFiles.setPreferredSize(Dimension(140, 20)) self.carouselLabel.setPreferredSize(Dimension(140, 20)) self.carouselStartingPosition.setPreferredSize(Dimension(170, 20)) panelList.add(btnU) panelList.add(panel) panelList.add(btnHideFile) panelList.add(btnShowAllFiles) panelList.add(JSeparator(JSeparator.HORIZONTAL), BorderLayout.LINE_START) panelList.add(self.carouselLabel) panelList.add(self.carouselStartingPosition) panelList.add(btnS) self.panelLabel = JPanel() self.panelLabel.add(self.label) self.standardBackgroundColor = self.panelLabel.getBackground() # put status label in a panel so that background color can be changed self.panelStatusLabel = JPanel() self.panelStatusLabel.add(self.statusLabel) # add widgets to frame self.frame.add(self.panelLabel, BorderLayout.NORTH) self.frame.add(panelList, BorderLayout.WEST) self.frame.add(panelTable, BorderLayout.CENTER) self.frame.add(self.panelStatusLabel, BorderLayout.SOUTH) self.frame.setVisible(True)