def initUI(self): panel = JPanel(size=(50, 50)) panel.setLayout(BorderLayout()) panel.setToolTipText("A Panel container") joclButton = JButton("JOCL") joclButton.setBounds(100, 500, 100, 30) joclButton.setToolTipText("JOCL Button") panel.add(joclButton) qButton = JButton("Quit", actionPerformed=self.onQuit) qButton.setBounds(200, 500, 80, 30) qButton.setToolTipText("Quit Button") panel.add(qButton) inputImage = ImageIcon("input.png") #JLabel imageLabel = inputImage label1 = JLabel(inputImage) label1.setBounds(1, 1, inputImage.getIconWidth(), inputImage.getIconHeight()) #label1.setVerticalTextPosition(JLabel.BOTTOM) #label1.setHorizontalTextPosition(JLabel.CENTER) #label1.setSize(1,1) panel.add(label1) self.getContentPane().add(panel) self.setTitle("GPU Demo") self.setSize(1200, 600) self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) self.setLocationRelativeTo(None) self.setVisible(True)
class Check(): """A check. For example: disconnected highways, duplicate nodes... """ def __init__(self, app, tool, view, (title, name, url, icon, marker)): self.tool = tool self.view = view #name and title if self.tool.isLocal: self.title = self.tool.title self.name = self.tool.name self.helpUrl = "" else: self.name = name if self.tool.isTranslated: self.title = self.tool.strings.getString("c_%s" % name) else: self.title = title self.helpUrl = self.tool.help_url(self) self.url = url if icon == "": self.icon = None else: self.icon = ImageIcon(File.separator.join([app.SCRIPTDIR, "tools", "data", self.tool.title.replace(" ", ""), "icons", "checks", "%s.png" % icon])) if marker == "": self.marker = None else: self.marker = ImageIcon(File.separator.join([app.SCRIPTDIR, "tools", "data", self.tool.title.replace(" ", ""), "icons", "checks", "%s.png" % marker])) self.bbox = None #self.currentErrorIndex = index of error currently being corrected in dialog self.currentErrorIndex = -1 #self.reviewedIds, list of ids of objects that have been checked (by pressing the next button) self.reviewedIds = [] #List of ids of OSM object that the user don't know how to correct #and that he/she doesn't want to see self.ignoreIds = [] #List of errors instances of this type of check self.errors = None #Number of errors that must be checked self.toDo = None
def load_image(name, data): var_name = "_{}_img".format(name) if _USE_EMBEDDED_IMAGES: globals()[var_name] = ImageIcon( StringUtil.toBytes(base64.b64decode(data))) else: globals()[var_name] = ImageIcon( file=os.path.join(os.path.dirname(__file__), name + ".gif"))
def initUI(self): panel = JPanel() panel.setLayout(None) panel.setBackground(Color(66, 66, 66)) self.getContentPane().add(panel) rot = ImageIcon("input.png") rotLabel = JLabel(rot) rotLabel.setBounds(20, 20, rot.getIconWidth(), rot.getIconHeight()) min = ImageIcon("cpuoutput.png") minLabel = JLabel(min) minLabel.setBounds(40, 160, min.getIconWidth(), min.getIconHeight()) bar = ImageIcon("inputdata.png") barLabel = JLabel(bar) barLabel.setBounds(170, 50, bar.getIconWidth(), bar.getIconHeight()) panel.add(rotLabel) panel.add(minLabel) panel.add(barLabel) self.setTitle("Absolute") self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) self.setSize(350, 300) self.setLocationRelativeTo(None) self.setVisible(True)
def __init__(self, app): #name: reference code for this tool used for exmaple in 'config.cfg' self.name = self.title.lower().replace(" ", "_") if self.name in app.toolsStatus: self.isActive = app.toolsStatus[self.name] else: self.isActive = True #localization if self.isTranslated: localeDir = File.separator.join([self.app.SCRIPTDIR, "tools", "data", self.title.replace(" ", ""), "locale"]) urls = [File(localeDir).toURI().toURL()] loader = URLClassLoader(urls) currentLocale = Locale.getDefault() self.strings = ResourceBundle.getBundle("MessagesBundle", currentLocale, loader) if self.name == "favourites": self.title = self.strings.getString("Favourites") if self.name == "favourites": ref = "Favourites" else: ref = self.title.replace(" ", "") self.bigIcon = ImageIcon(File.separator.join([app.SCRIPTDIR, "tools", "data", ref, "icons", "tool_24.png"])) self.smallIcon = ImageIcon(File.separator.join([app.SCRIPTDIR, "tools", "data", ref, "icons", "tool_16.png"])) if not hasattr(self, "isLocal") or not self.isLocal: self.isLocal = False if self.name in app.toolsPrefs: self.update_preferences() if not hasattr(self, "markerPosition"): self.markerPosition = None self.views = [] for viewName, checksList in self.toolInfo.iteritems(): self.views.append(View(app, self, viewName, checksList))
def load_icon(self): with open("icon_arrow--green.jpg", "rb") as in_file: pic = in_file.read() print(pic) try: self.icon = ImageIcon(pic, "CompuRacerIcon") except Exception as e: print(e) print("Cannot load image!") print(self.icon) print(self.icon.getImageLoadStatus()) print(self.icon.getImageObserver())
def init(self): self.getContext().addPropertyChangeListener(self) #ThrottleFrame change self.getContext().getCurrentThrottleFrame().getAddressPanel().addAddressListener(self) # change of throttle in Current frame self.addressPanel = self.getContext().getCurrentThrottleFrame().getAddressPanel() self.throttle = self.addressPanel.getThrottle() # the throttle self.roster = self.addressPanel.getRosterEntry() # roster entry if any self.speedAction = SpeedAction() #Speed increase thread self.speedAction.setThrottle( self.throttle ) self.speedTimer = Timer(valueSpeedTimerRepeat, self.speedAction ) # Very important to use swing Timer object (see Swing and multithreading doc) self.speedTimer.setRepeats(True) self.label = JButton(ImageIcon(self.getFolder() + "/USBControl.png","USBThrottle")) #label self.label.addMouseListener(self.getMouseListeners()[0]) # In order to get the popupmenu on the button too self.add(self.label) self.model = jmri.jmrix.jinput.TreeModel.instance() # USB self.desiredController = None self.ctrlMenuItem = [] self.USBDriver = None self.driver = None mi = JCheckBoxMenuItem ("None") self.getPopUpMenu().add( mi ) mi.addItemListener( ControllerItemListener(None, self) ) self.ctrlMenuItem.append(mi) for ctrl in self.model.controllers(): mi = JCheckBoxMenuItem (ctrl.getName()) self.getPopUpMenu().add( mi ) mi.addItemListener( ControllerItemListener(ctrl, self) ) self.ctrlMenuItem.append(mi) if ( len(self.ctrlMenuItem) == 0 ): print "No matching USB device found" else: self.ctrlMenuItem[0].setSelected(True) # by default connect to the first one self.model.addPropertyChangeListener(self) self.lastTimeStopButton = Calendar.getInstance().getTimeInMillis() self.lastTimeCruiseButton = Calendar.getInstance().getTimeInMillis()
def init(self): self.getContext().addPropertyChangeListener( self) #ThrottleFrame change self.addressPanel = self.getContext().getCurrentThrottleFrame( ).getAddressPanel() self.addressPanel.addAddressListener( self) # change of throttle in Current frame self.throttle = self.getContext().getCurrentThrottleFrame( ).getAddressPanel().getThrottle() # the throttle self.speedAction = SpeedAction() #Speed increase thread self.speedAction.setThrottle(self.throttle) self.speedTimer = Timer( valueSpeedTimerRepeat, self.speedAction ) # Very important to use swing Timer object (see Swing and multithreading doc) self.speedTimer.setRepeats(True) self.label = JButton( ImageIcon(self.getFolder() + "/WiimoteThrottle2.png", "WiiMote")) #label self.label.addMouseListener( self.getMouseListeners() [0]) # In order to get the popupmenu on the button too self.add(self.label) self.lastTimeButton1 = Calendar.getInstance().getTimeInMillis() self.lastTimeButton2 = Calendar.getInstance().getTimeInMillis() self.advFunctions = AdvFunctions() self.lastTimeEStop = Calendar.getInstance().getTimeInMillis() self.wiiDevice = None self.sync = thread.allocate_lock() # A lock protecting bellow self.evt self.evt = None java.lang.System.setProperty("bluecove.jsr82.psm_minimum_off", "true") # Required for Bluecove + WiiRemoteJ WiiRemoteJ.findRemotes(self, 1) # Search for 1 Wiimote, and call back
def onInfo(self, e): info = JFrame() info.setTitle("Info") info.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE) info.setSize(410, 400) info.setLocationRelativeTo(None) info.setResizable(False) info.setVisible(True) panel = JPanel() #panel.setBackground(Color(46, 64, 96)) #panel.setLayout(GridLayout(0, 2)) logo = JLabel(ImageIcon("/icons/logo.jpg")) panel.add(logo) f = Font("", Font.ITALIC, 40) title = JLabel("Stylus OS 1.0 beta") title.setFont(f) panel.add(title) f = Font("", Font.ITALIC, 14) copyright = JLabel( "Copyright (c) 2016 Niccolo' Ciavarella. All rights reserved.") copyright.setFont(f) panel.add(copyright) info.getContentPane().add(panel) info.add(panel)
def __init__(self, filename, width=None, height=None): """Create an image from a file, or an empty (black) image with specified dimensions.""" # Since Python does not allow constructors with different signatures, # the trick is to reuse the first argument as a filename or a width. # If it is a string, we assume they want is to open a file. # If it is an int, we assume they want us to create a blank image. if type(filename) == type(""): # is it a string? self.filename = filename # treat is a filename self.image = BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB) # create a dummy image self.read(filename) # and read external image into ti elif type(filename) == type(1): # is it a int? # create blank image with specified dimensions self.filename = "Untitled" self.width = filename # holds image width (shift arguments) self.height = width # holds image height self.image = BufferedImage(self.width, self.height, BufferedImage.TYPE_INT_RGB) # holds image buffer (pixels) else: raise TypeError("Image(): first argument must a filename (string) or an blank image width (int).") # display image self.display = JFrame() # create frame window to hold image icon = ImageIcon(self.image) # wrap image appropriately for displaying in a frame container = JLabel(icon) self.display.setContentPane(container) # and place it self.display.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) self.display.setTitle(self.filename) self.display.setResizable(False) self.display.pack() self.display.setVisible(True)
def gui_open(path): label = JLabel(ImageIcon(ImageIO.read(File(URL(path).getFile())))) frame = JFrame() frame.getContentPane().add(label) frame.pack() frame.setLocation(200, 200) frame.setVisible(True)
This is the main class. Figure: Moving sprite Shooting missiles In the next example we add another sprite type to our example—a missile. The missiles are launched with the Space key. Sprite.java package com.zetcode; import java.awt.Image; import javax.swing.ImageIcon; public class Sprite { protected int x; protected int y; protected int width; protected int height; protected boolean visible; protected Image image; public Sprite(int x, int y) { this.x = x; this.y = y; visible = true; } protected void loadImage(String imageName) { ImageIcon ii = new ImageIcon(imageName); image = ii.getImage(); } protected void getImageDimensions() { width = image.getWidth(null); height = image.getHeight(null); } public Image getImage() { return image; } public int getX() { return x; } public int getY() { return y; } public boolean isVisible() { return visible; } public void setVisible(Boolean visible) { this.visible = visible; } }
def two( self, event ) : JOptionPane.showMessageDialog( self.frame, 'Green Eggs & Spam!', 'A complete breakfast', JOptionPane.INFORMATION_MESSAGE, ImageIcon( URL( 'file:///C:/temp/GreenEgg.gif' ) ) )
def initUI(self): self.manImage = ImageIcon('bin/gui/media/' + "danglewood.gif") self.manImageSilent = ImageIcon('bin/gui/media/' + "danglewood-silent.png") self.manLabel = JLabel(self.manImage) self.dialogText = JTextPane() self.dialogText.setEditable(False) self.dialogTextScroller = JScrollPane(self.dialogText) self.dialogText.setBackground(Color(0, 24, 0)) self.dialogText.setForeground(Color.WHITE) self.dialogText.setFont(Font("Arial", Font.BOLD, 15)) self.buttonsPanel = ButtonPanel(self.consolePanel, self) self.dialogText.setText("Welcome to BashED!!!")
def set_mario(self, button): # Draws Mario in a given button. # # Parameters: # button to set Mario icon to. button.setIcon(ImageIcon(self.resources_directory + self.mario))
def __init__(self): UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()) size = Dimension(800, 800) self.setPreferredSize(size) screenSize = Toolkit.getDefaultToolkit().getScreenSize() self.setLocation(screenSize.getSize().width / 2 - size.width / 2, 100) self.setTitle("bashED Terminal HQ EXTREME") self.setUndecorated(True) self.getRootPane().setOpaque(False) #self.getRootPane().setWindowDecorationStyle(JRootPane.FRAME); self.setBackground(Color(0, 128, 0, 198)) #j = JDesktopPane() #j.setOpaque(False) self.setLayout(None) self.setIconImage(ImageIcon('bin/gui/media/' + "icon.png").getImage()) mp = MainPanel() self.add(mp) mp.setBounds(0, 0, size.width, size.height) imageTest = ImageIcon('bin/gui/media/' + "image.png") imageTestLabel = JLabel(imageTest) self.add(imageTestLabel) imageTestLabel.setBounds(0, 0, size.width, size.height) #self.getContentPane().add(mp) #self.getContentPane().add(JLabel("Iglo")) bb = BorderFactory.createLineBorder(Color.BLACK, 5) bw1 = BorderFactory.createLineBorder(Color.WHITE, 1) bw2 = BorderFactory.createLineBorder(Color.WHITE, 1) mp.setBorder( BorderFactory.createCompoundBorder( bw1, BorderFactory.createCompoundBorder(bb, bw2))) #make the window viewable self.defaultCloseOperation = JFrame.EXIT_ON_CLOSE self.pack() self.setVisible(True)
def create_icon(self, path): try: im = ImageIO.read(File(path)) except: raise im = im.getScaledInstance(32, 32, Image.SCALE_SMOOTH) icon = ImageIcon(im) return icon
def __init__(self, app, menuTitle): JMenu.__init__(self, menuTitle) self.app = app #quat dialog item dialogItem = JCheckBoxMenuItem(self.app.dlg.toggleAction) self.add(dialogItem) self.addSeparator() #tool submenu for tool in self.app.tools: if tool.name == "favourites": self.addSeparator() toolMenu = JMenu(tool.title) toolMenu.setIcon(tool.bigIcon) if tool.uri != "": #Website link iconFile = File.separator.join( [self.app.SCRIPTDIR, "images", "icons", "browser.png"]) urlItem = JMenuItem(tool.title) urlItem.setIcon(ImageIcon(iconFile)) urlItem.addActionListener( QatMenuActionListener(self.app, "link", tool)) toolMenu.add(urlItem) toolMenu.addSeparator() #View submenu for view in tool.views: viewMenu = JMenu(view.title) if tool.name == "favourites": self.app.favouritesMenu = viewMenu #Check item for check in view.checks: self.add_check_item(tool, view, check, viewMenu) toolMenu.add(viewMenu) self.add(toolMenu) #Local file with errors localFileItem = JMenuItem(self.app.strings.getString("Open_GPX")) localFileItem.setIcon(ImageProvider.get("open")) localFileItem.addActionListener( QatMenuActionListener(self.app, "local file")) self.add(localFileItem) self.addSeparator() #False positive dialog falsepositiveItem = JMenuItem( self.app.strings.getString("False_positives...")) falsepositiveItem.addActionListener( QatMenuActionListener(self.app, "dialog")) self.add(falsepositiveItem) #Preferences dialog preferencesItem = JMenuItem( self.app.strings.getString("Preferences...")) preferencesItem.addActionListener( QatMenuActionListener(self.app, "dialog")) self.add(preferencesItem) #About dialog item aboutItem = JMenuItem(self.app.strings.getString("About...")) aboutItem.addActionListener(QatMenuActionListener(self.app, "dialog")) self.add(aboutItem)
def setValue(self, value): if value == "": img = BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB) g = img.getGraphics() g.setColor(Color.RED) g.fillOval(2, 2, 10, 10) self.setIcon(ImageIcon(img)) else: self.setIcon(value)
def initUI(self): self.setBackground(Color.black) iid = ImageIcon("dot.png") self.ball = iid.getImage() iia = ImageIcon("apple.png") self.apple = iia.getImage() iih = ImageIcon("head.png") self.head = iih.getImage() self.setFocusable(True) self.addKeyListener(self) self.initGame()
class spyMonitor(JButton, ActionListener): # Static data (shared by all instances) # I hope this reduces memory/improves speed... yellowLED = ImageIcon("GIF/yellow.gif") redLED = ImageIcon("GIF/red.gif") greenLED = ImageIcon("GIF/green.gif") def __init__(self, spy, parentCrate=None): JButton.__init__(self) self.spy = spy self.parentCrate = parentCrate self.text = "0" self.icon = self.redLED self.addActionListener(self) self.margin = Insets(1, 1, 1, 1) self.focusPainted = 0 self.borderPainted = 0 def actionPerformed(self, event): if __debug__: print self.spy.name if self.parentCrate != None: self.parentCrate.setMonitoredSpy(self.spy) def update(self): oldPtrValue = self.spy.ptr.value oldWrpValue = self.spy.wrp.value self.spy.read() # wrap counter if oldWrpValue != self.spy.wrp.value: self.text = "%d" % self.spy.wrp.value # colored LED if self.spy.frz.value: icon = self.yellowLED elif self.spy.ptr.value == oldPtrValue: icon = self.redLED else: icon = self.greenLED if self.icon != icon: self.icon = icon self.toolTipText = "%5.5x" % self.spy.ptr.value
def getIcon(self): """Set the layer icon. """ if self.iconf is not None: return self.iconf else: img = BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB) g = img.getGraphics() g.setColor(Color.RED) g.fillOval(2, 2, 10, 10) return ImageIcon(img)
def set_dizzy(self, button): # Draws Dizzy in a given button, sets game status to "Playing" and # plays action sound. # # Parameters: # button to set Dizzy icon to. button.setIcon(ImageIcon(self.resources_directory + self.dizzy)) self.status_label.setText(self.in_game_status) self.play_sound_safe(self.action_sound)
def initUI(self): self.panel = JPanel(size=(50, 50)) self.panel.setLayout(FlowLayout()) self.panel.setToolTipText("GPU Demo") self.textfield1 = JTextField('Smoothing Parameter', 15) self.panel.add(self.textfield1) joclButton = JButton("JOCL", actionPerformed=self.onJocl) joclButton.setBounds(100, 500, 100, 30) joclButton.setToolTipText("JOCL Button") self.panel.add(joclButton) javaButton = JButton("Java", actionPerformed=self.onJava) javaButton.setBounds(100, 500, 100, 30) javaButton.setToolTipText("Java Button") self.panel.add(javaButton) qButton = JButton("Quit", actionPerformed=self.onQuit) qButton.setBounds(200, 500, 80, 30) qButton.setToolTipText("Quit Button") self.panel.add(qButton) newImage = ImageIO.read(io.File("input.png")) resizedImage = newImage.getScaledInstance(600, 600, 10) newIcon = ImageIcon(resizedImage) label1 = JLabel("Input Image", newIcon, JLabel.CENTER) label1.setVerticalTextPosition(JLabel.TOP) label1.setHorizontalTextPosition(JLabel.RIGHT) label1.setSize(10, 10) label1.setBackground(Color.orange) self.panel.add(label1) self.getContentPane().add(self.panel) self.clockLabel = JLabel() self.clockLabel.setSize(1, 1) self.clockLabel.setBackground(Color.orange) self.clockLabel.setVerticalTextPosition(JLabel.BOTTOM) self.clockLabel.setHorizontalTextPosition(JLabel.LEFT) myClockFont = Font("Serif", Font.PLAIN, 50) self.clockLabel.setFont(myClockFont) self.panel.add(self.clockLabel) self.setTitle("GPU Demo") self.setSize(1200, 600) self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) self.setLocationRelativeTo(None) self.setVisible(True)
def updateProduct(self, *args): try: value = self.lstProducts.getSelectedValue() except: return if value == None: return #try: if True: width = 150 height = 150 #gvSIGPath = Utilities.TEMPDIRECTORYPATH gvSIGPath = "/home/osc/temp" outputPath = os.path.join( gvSIGPath, value.getName() + "_%sx%s.jpg" % (width, height)) #Utilities.TEMPDIRECTORYPATH if os.path.exists(outputPath) == False: url = value.getPreviewLink() f = download(url) total_size = int(f.headers["Content-Length"]) MB_size = round(total_size / 1048576, 2) block_size = 1024 * 1024 outputPathFull = gvSIGPath + value.getName() + ".jpg" with open(outputPath, "wb") as file: while True: block = f.read(block_size) dSize = round( int(os.stat(outputPath).st_size) / 1048576, 2) print "(" + str(dSize) + "/" + str( MB_size) + " MB) " + url + "Downloading" if not block: break file.write(block) img = ImageIO.read(outputPathFull) tmp = img.getScaledInstance(width, height, Image.SCALE_SMOOTH) resized = BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) g2d = resized.createGraphics() g2d.drawImage(tmp, 0, 0, None) g2d.dispose() ImageIO.write(resized, "jpg", outputPath) else: print "already downloaded" myPicture = ImageIcon(ImageIO.read(File(outputPath))) self.txtInfo.setText(value.getInfoString()) self.tabInfo.updateUI() self.lstProducts.updateUI() self.lstProducts.revalidate() self.lstProducts.repaint() #except: # myPicture = ImageIcon() self.lblPreview.setIcon(myPicture)
def start(self, event): self.button.setEnabled(0) self.PM = ProgressMonitor( None, # parentComponent ImageIcon(URL('file:///C:/temp/GreenEgg.gif')), None, # note 0, # minimum value 100 # maximum value ) self.task = progressTask(self.propertyUpdate) self.task.execute()
def loadImageIcon(path, classloader=None): """Loads an image resource as an ImageIcon from anywhere on the class path. :param path: Path to the resource (separate elements with '/') :param classloader: class loader to use for loading the resource :rtype: :class:`javax.swing.ImageIcon` """ from javax.swing import ImageIcon resource = getResource(path, classloader) return ImageIcon(resource)
def restart(self): self.dizzy = None self.dizzy = self.choosePlayer() self.winner = None self.board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] for button in self.buttons: button.setIcon(ImageIcon(self.resources_directory + self.blank)) self.stop_playing_background() self.sound = self.play_sound_safe(self.sounds[self.last_sound]) self.last_sound = self.last_sound + 1 if self.last_sound >= len(self.sounds): self.last_sound = 0 self.status_label.setText(self.welcome_status)
def onExit(self, e): exit = JFrame() exit.setTitle("Exit Stylus") exit.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE) exit.setSize(250, 225) exit.setLocationRelativeTo(None) exit.setVisible(True) exit.setResizable(False) panel = JPanel() panel.setBorder(BorderFactory.createEtchedBorder()) panel.setLayout(GridLayout(0, 1)) exit.getContentPane().add(panel) icon1 = ImageIcon("/icons/shutdown.png") poweroff = JButton("Shutdown", icon1, actionPerformed=self.shutdown) panel.add(poweroff) icon2 = ImageIcon("/icons/reboot.png") reboot = JButton(" Reboot ", icon2, actionPerformed=self.reboot) panel.add(reboot) exit.add(panel)
def create_icon(self, path): # try : # im = ImageIO.read(File(path)) # im_url = self.getClass().getResource(path) # im = ImageIO.read(im_url) ins = self.getClass().getResourceAsStream(path) # reader = BufferedReader(InputStreamReader(is)) im = ImageIO.read(ins) # except : # raise im = im.getScaledInstance(32, 32, Image.SCALE_SMOOTH) icon = ImageIcon(im) return icon
def showTweet(self, status): user = status.user p = JPanel() p.add(JLabel(ImageIcon(URL(user.profile_image_url)))) p.add( JTextArea(text=status.text, editable=False, wrapStyleWord=True, lineWrap=True, alignmentX=Component.LEFT_ALIGNMENT, size=(300, 1))) self.resultPanel.add(p)
def initUI(self): panel = JPanel(size=(50,50)) panel.setLayout(BorderLayout( )) panel.setToolTipText("A Panel container") joclButton = JButton("JOCL") joclButton.setBounds(100, 500, 100, 30) joclButton.setToolTipText("JOCL Button") panel.add(joclButton) qButton = JButton("Quit", actionPerformed=self.onQuit) qButton.setBounds(200, 500, 80, 30) qButton.setToolTipText("Quit Button") panel.add(qButton) inputImage = ImageIcon("input.png") #JLabel imageLabel = inputImage label1 = JLabel(inputImage) label1.setBounds(1, 1, inputImage.getIconWidth(), inputImage.getIconHeight()) #label1.setVerticalTextPosition(JLabel.BOTTOM) #label1.setHorizontalTextPosition(JLabel.CENTER) #label1.setSize(1,1) panel.add(label1) self.getContentPane().add(panel) self.setTitle("GPU Demo") self.setSize(1200, 600) self.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) self.setLocationRelativeTo(None) self.setVisible(True)
def __init__(self): JFrame.__init__(self, "SwingingMonkeyCommander", \ layout=BorderLayout(), \ size=(505, 874), \ defaultCloseOperation=JFrame.EXIT_ON_CLOSE,) \ scriptDir = os.path.realpath(os.path.dirname(sys.argv[0])) self.frameIcon = ImageIcon(scriptDir + '/smcs.png') self.setIconImage(self.frameIcon.getImage()) self.image = ImageIcon() self.label = JLabel(self.image) self.scrollpane = JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) self.scrollpane.addMouseListener(ScreenMouseListener(self)) self.keyListener = ScreenKeyListener(self) self.initAndroidKeyMap() self.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET); self.scrollpane.preferredSize = self._preferredWidth, self._preferredHeight self.scrollpane.viewport.view = self.label self.label.preferredSize = (self._preferredWidth, self._preferredHeight) self.add(self.scrollpane, BorderLayout.PAGE_START) self.show() self.androidDevice = None if self.waitForAndroidDeviceConnection() == False: print "Could not establish connection with device." return self.screenPullTask = ScreenPullTask(self) self.screenPullTask.execute() self.dragStart = (0,0) self.dragEnd = (0,0)
def initUI(self): self.setBackground(Color(0, 50, 0)) self.playButtonS = ImageIcon('bin/gui/media/' + "playButton.png") self.helpButtonS = ImageIcon('bin/gui/media/' + "helpButton.png") self.resetButtonS = ImageIcon('bin/gui/media/' + "resetButton.png") self.exitButtonS = ImageIcon('bin/gui/media/' + "exitButton.png") self.playButtonU = ImageIcon('bin/gui/media/' + "playButton_unselected.png") self.helpButtonU = ImageIcon('bin/gui/media/' + "helpButton_unselected.png") self.resetButtonU = ImageIcon('bin/gui/media/' + "resetButton_unselected.png") self.exitButtonU = ImageIcon('bin/gui/media/' + "exitButton_unselected.png") class MouseHoverAdap(MouseAdapter): def __init__(self, butt, entImage, leaImage): self.entImage = entImage self.leaImage = leaImage self.butt = butt self.butt.setIcon(self.leaImage) def mouseEntered(self, m): self.butt.setIcon(self.entImage) #self.butt.repaint() def mouseExited(self, m): self.butt.setIcon(self.leaImage) #self.butt.repaint() self.playButton = JButton(self.playButtonS) self.playButton.setForeground(Color(0, 245, 0)) #self.playButton.setPreferredSize(Dimension(playButton.getIconWidth(), playButton.getIconHeight())) #self.playButton.setBackground(Color(125, 125, 25)) self.playButton.setMaximumSize(Dimension(self.playButtonS.getIconWidth(), self.playButtonS.getIconHeight())) self.playButton.setContentAreaFilled(False) self.helpButton = JButton(self.helpButtonS) self.helpButton.setForeground(Color(0, 235, 0)) self.helpButton.setMaximumSize(Dimension(self.helpButtonS.getIconWidth(), self.helpButtonS.getIconHeight())) self.helpButton.setContentAreaFilled(False) self.resetButton = JButton(self.resetButtonS) self.resetButton.setForeground(Color(0, 225, 0)) self.resetButton.setMaximumSize(Dimension(self.resetButtonS.getIconWidth(), self.resetButtonS.getIconHeight())) self.resetButton.setContentAreaFilled(False) self.exitButton = JButton(self.exitButtonS) self.exitButton.setForeground(Color(0, 215, 0)) self.exitButton.setContentAreaFilled(False) self.exitButton.setMaximumSize(Dimension(self.exitButtonS.getIconWidth(), self.exitButtonS.getIconHeight())) # self.playButton.addMouseListener(MouseHoverAdap(self.playButton, self.playButtonS, self.playButtonU)) # self.helpButton.addMouseListener(MouseHoverAdap(self.helpButton, self.helpButtonS, self.helpButtonU)) # self.resetButton.addMouseListener(MouseHoverAdap(self.resetButton, self.resetButtonS, self.resetButtonU)) # self.exitButton.addMouseListener(MouseHoverAdap(self.exitButton, self.exitButtonS, self.exitButtonU)) class PlayButtonActionListener(ActionListener): def actionPerformed(button, e): self.dialogPanel.speak(self.consolePanel.console.do_play('')) self.playButton.addActionListener(PlayButtonActionListener()) class HelpBUttonActionListener(ActionListener): def actionPerformed(button, e): self.dialogPanel.speak(self.consolePanel.console.do_hint('')) self.helpButton.addActionListener(HelpBUttonActionListener()) class ResetButtonActionListener(ActionListener): def actionPerformed(button, e): self.dialogPanel.speak(self.consolePanel.console.do_reset('')) self.resetButton.addActionListener(ResetButtonActionListener()) class ExitButtonActionListener(ActionListener): def actionPerformed(button, e): System.exit(0) self.exitButton.addActionListener(ExitButtonActionListener())
def __init__(self): self.panel = JPanel() self.panel.setLayout(BorderLayout()) frame = JFrame("GUI Development ") frame.setSize(800, 600) frame.setLayout(BorderLayout()) splitPane = JSplitPane(JSplitPane.VERTICAL_SPLIT); self.textfield1 = JTextField('Type something here') self.textfield1.setColumns(40); #self.textfield1.setRows(5); #self.textfield2 = JTextField('Dont write anythong',30) label1 = JLabel("Command:") panel1 = JPanel() ''' ''' jMenuBar1 = JMenuBar() jMenu1 = JMenu() jMenu2 = JMenu() jMenuItem1 = JMenuItem('Open', actionPerformed=self.onClick) jMenuItem2 = JMenuItem() jMenu1.setText('File') jMenu2.setText('Simulation') #jMenuItem1.setText('Open') jMenuItem2.setText('Exit') jMenu1.add(jMenuItem1) jMenu1.add(jMenuItem2) jMenuBar1.add(jMenu1) jMenuItem21 = JMenuItem('Simulation Options',actionPerformed=self.writeText) jMenuItem22 = JMenuItem('Simulate',actionPerformed=self.writeText) jMenuItem23 = JMenuItem('Generate FMU',actionPerformed=self.writeText) # jMenuItem21.setText('Run Project') # jMenuItem22.setText('Generate FMU') jMenu2.add(jMenuItem21) jMenu2.add(jMenuItem22) jMenu2.add(jMenuItem23) jMenuBar1.add(jMenu2) frame.setJMenuBar(jMenuBar1) ''' ''' panel1.add(label1,BorderLayout.WEST) panel1.add(self.textfield1, BorderLayout.CENTER) copyButton = JButton('send',actionPerformed=self.copyText) panel1.add(copyButton, BorderLayout.EAST) #panel1.add(self.textfield2, BorderLayout.SOUTH) splitPane.setLeftComponent(panel1); ''' image adding in the frame ''' #imPanel.add(imPanel,BorderLayout.WEST) #imPanel.setBackground(Color(66, 66, 66)) imPanel1 = JPanel() rot = ImageIcon("ballon.jpg") rotLabel = JLabel(rot) rotLabel.setBounds(0,0, rot.getIconWidth(), rot.getIconHeight()) imPanel1.add(rotLabel, BorderLayout.SOUTH) frame.add(imPanel1, BorderLayout.SOUTH) ''' panel for text area adding in split pan ''' tabPane = JTabbedPane(JTabbedPane.TOP) label = JLabel("<html><br>This is a tab1</html>") panel1 = JPanel() panel1.setBackground(Color.lightGray) panel23 = JPanel() panel23.setBackground(Color.black) panel1.add(panel23,BorderLayout.SOUTH) panel1.add(label,BorderLayout.NORTH) ''' adding button in the panel1 ''' writeButton = JButton('write') panel1.add(writeButton, BorderLayout.WEST) tabPane.addTab("tab1", panel1) #frame.add(panel1,BorderLayout.EAST) #panel1.setBackground(Color(66, 66, 66)) # rot1 = ImageIcon("ballon.jpg",BorderLayout.SOUTH) # rotLabel1 = JLabel(rot1) # rotLabel1.setBounds(0,0, rot.getIconWidth(), rot.getIconHeight()) # panel1.add(rotLabel1) label2 = JLabel("This is a tab2") panel2 = JPanel() panel2.setBackground(Color.lightGray) panel2.add(label2) tabPane.addTab("tab2", panel2) # imPanel2 =JPanel() self.textarea = JTextArea('Write something from commandLine') self.textarea.setColumns(40); self.textarea.setRows(40); panel2.add(self.textarea, BorderLayout.NORTH) splitPane.setRightComponent(tabPane); splitPane.setDividerLocation(60); frame.add(splitPane) frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) frame.setVisible(True)
class SwingingMonkeyCommander(JFrame): ''' A Jython tool that uses the Android SDK's monkeyrunner to communicate with the device. It fetches screenshots and draws them in the desktop window and can accept mouse and key events. Author: Fredrik Henricsson ([email protected]) ''' _preferredWidth = 480 _preferredHeight = 854 _widthScale = 1.0 _heightScale = 1.0 def __init__(self): JFrame.__init__(self, "SwingingMonkeyCommander", \ layout=BorderLayout(), \ size=(505, 874), \ defaultCloseOperation=JFrame.EXIT_ON_CLOSE,) \ scriptDir = os.path.realpath(os.path.dirname(sys.argv[0])) self.frameIcon = ImageIcon(scriptDir + '/smcs.png') self.setIconImage(self.frameIcon.getImage()) self.image = ImageIcon() self.label = JLabel(self.image) self.scrollpane = JScrollPane(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED) self.scrollpane.addMouseListener(ScreenMouseListener(self)) self.keyListener = ScreenKeyListener(self) self.initAndroidKeyMap() self.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, Collections.EMPTY_SET); self.scrollpane.preferredSize = self._preferredWidth, self._preferredHeight self.scrollpane.viewport.view = self.label self.label.preferredSize = (self._preferredWidth, self._preferredHeight) self.add(self.scrollpane, BorderLayout.PAGE_START) self.show() self.androidDevice = None if self.waitForAndroidDeviceConnection() == False: print "Could not establish connection with device." return self.screenPullTask = ScreenPullTask(self) self.screenPullTask.execute() self.dragStart = (0,0) self.dragEnd = (0,0) def waitForAndroidDeviceConnection(self): maxAttempts = 5 secondsBetweenAttempts = 5 attempts = 0 while(self.androidDevice == None or attempts >= maxAttempts): if attempts > 0: print "Could not connect to Android device. Trying again in 5 seconds." time.sleep(secondsBetweenAttempts) self.androidDevice = MonkeyRunner.waitForConnection() attempts += 1 if self.androidDevice != None: return True else: return False def initAndroidKeyMap(self): # TODO: Can we use a tuple for the key and use keyCode as the first, # and keyLocation as the second value? # TODO: Need to check modifiers as well. # TODO: Do we need to consider the locale or does Java abstract that away? self.keyMap = { KeyEvent.VK_A : 'KEYCODE_A', KeyEvent.VK_B : 'KEYCODE_B', KeyEvent.VK_C : 'KEYCODE_C', KeyEvent.VK_D : 'KEYCODE_D', KeyEvent.VK_E : 'KEYCODE_E', KeyEvent.VK_F : 'KEYCODE_F', KeyEvent.VK_G : 'KEYCODE_G', KeyEvent.VK_H : 'KEYCODE_H', KeyEvent.VK_I : 'KEYCODE_I', KeyEvent.VK_J : 'KEYCODE_J', KeyEvent.VK_K : 'KEYCODE_K', KeyEvent.VK_L : 'KEYCODE_L', KeyEvent.VK_M : 'KEYCODE_M', KeyEvent.VK_N : 'KEYCODE_N', KeyEvent.VK_O : 'KEYCODE_O', KeyEvent.VK_P : 'KEYCODE_P', KeyEvent.VK_Q : 'KEYCODE_Q', KeyEvent.VK_R : 'KEYCODE_R', KeyEvent.VK_S : 'KEYCODE_S', KeyEvent.VK_T : 'KEYCODE_T', KeyEvent.VK_U : 'KEYCODE_U', KeyEvent.VK_V : 'KEYCODE_V', KeyEvent.VK_W : 'KEYCODE_W', KeyEvent.VK_X : 'KEYCODE_X', KeyEvent.VK_Y : 'KEYCODE_Y', KeyEvent.VK_Z : 'KEYCODE_Z', KeyEvent.VK_0 : 'KEYCODE_0', KeyEvent.VK_1 : 'KEYCODE_1', KeyEvent.VK_2 : 'KEYCODE_2', KeyEvent.VK_3 : 'KEYCODE_3', KeyEvent.VK_4 : 'KEYCODE_4', KeyEvent.VK_5 : 'KEYCODE_5', KeyEvent.VK_6 : 'KEYCODE_6', KeyEvent.VK_7 : 'KEYCODE_7', KeyEvent.VK_8 : 'KEYCODE_8', KeyEvent.VK_9 : 'KEYCODE_9', KeyEvent.VK_NUMPAD0 : 'KEYCODE_NUMPAD_0', KeyEvent.VK_NUMPAD1 : 'KEYCODE_NUMPAD_1', KeyEvent.VK_NUMPAD2 : 'KEYCODE_NUMPAD_2', KeyEvent.VK_NUMPAD3 : 'KEYCODE_NUMPAD_3', KeyEvent.VK_NUMPAD4 : 'KEYCODE_NUMPAD_4', KeyEvent.VK_NUMPAD5 : 'KEYCODE_NUMPAD_5', KeyEvent.VK_NUMPAD6 : 'KEYCODE_NUMPAD_6', KeyEvent.VK_NUMPAD7 : 'KEYCODE_NUMPAD_7', KeyEvent.VK_NUMPAD8 : 'KEYCODE_NUMPAD_8', KeyEvent.VK_NUMPAD9 : 'KEYCODE_NUMPAD_9', KeyEvent.VK_BACK_SPACE : 'KEYCODE_DEL', KeyEvent.VK_ENTER : 'KEYCODE_ENTER', KeyEvent.VK_SPACE : 'KEYCODE_SPACE', KeyEvent.VK_SHIFT : 'KEYCODE_SHIFT_LEFT', KeyEvent.VK_CONTROL : 'KEYCODE_CONTROL_LEFT', KeyEvent.VK_CAPS_LOCK : 'KEYCODE_CAPS_LOCK', KeyEvent.VK_ESCAPE : 'KEYCODE_ESCAPE', KeyEvent.VK_ALT : 'KEYCODE_ALT_LEFT', KeyEvent.VK_PAGE_UP : 'KEYCODE_PAGE_UP', KeyEvent.VK_PAGE_DOWN : 'KEYCODE_PAGE_DOWN', KeyEvent.VK_LEFT : 'KEYCODE_DPAD_LEFT', KeyEvent.VK_RIGHT : 'KEYCODE_DPAD_RIGHT', KeyEvent.VK_UP : 'KEYCODE_DPAD_UP', KeyEvent.VK_DOWN : 'KEYCODE_DPAD_DOWN', KeyEvent.VK_INSERT : 'KEYCODE_INSERT', KeyEvent.VK_HOME : 'KEYCODE_HOME', KeyEvent.VK_NUM_LOCK : 'KEYCODE_NUM_LOCK', KeyEvent.VK_SCROLL_LOCK : 'KEYCODE_SCROLL_LOCK', KeyEvent.VK_PAUSE : 'KEYCODE_BREAK', KeyEvent.VK_TAB : 'KEYCODE_TAB', KeyEvent.VK_SEMICOLON : 'KEYCODE_SEMICOLON', } def sendMouseEvent(self, event): #print "Mouse pressed: " + str(event.getX()) + " " + str(event.getY() - yAdj) translatedX = int(event.getX() * self._widthScale) translatedY = int(event.getY() * self._heightScale) self.androidDevice.touch(translatedX, translatedY, MonkeyDevice.DOWN_AND_UP) def sendDragEvent(self): self.androidDevice.drag(self.dragStart, self.dragEnd, 1.0, 10) def sendKeyEvent(self, event, action): print event androidKey = '' #keyLocation = event.getKeyLocation() #if (keyLocation == KeyEvent.KEY_LOCATION_LEFT) or (keyLocation == KeyEvent.KEY_LOCATION_RIGHT): # androidKey = self.keyMap[event.getKeyCode() + "_" + keyLocation] #else: androidKey = self.keyMap[event.getKeyCode()] print "Android KeyEvent: " + androidKey self.androidDevice.press(androidKey, action)