예제 #1
0
def tree():
  """
  tree(xmlfile="dsm2.xml")
    creates a tree view on a given xml file of dsm2 input data
  """
  tv = TreeViewer()
  mp2 = JPanel()
  mp2.setLayout(BorderLayout())
  tf = JTextField("dsm2.inp")
  pb = JButton("parse")
  mp2.add(tf,BorderLayout.CENTER)
  mp2.add(pb,BorderLayout.EAST)
  class ParseListener(ActionListener):
    def __init__(self,tf,tv,fr):
      self.tf = tf
      self.tv = tv
      self.fr = fr
    def actionPerformed(self,evt):
      dsm2file = self.tf.getText()
      parser = DSM2Parser(dsm2file)
      self.tv.xdoc = parser.dsm2_data.toXml()
      self.fr.getContentPane().add(self.tv.gui(),BorderLayout.CENTER)
      self.fr.pack()
      self.fr.setVisible(1)
  fr = JFrame()
  fr.setTitle("DSM2Tree")
  fr.setLocation(100,100)
  fr.setSize(600,60)
  fr.getContentPane().setLayout(BorderLayout())
  fr.getContentPane().add(mp2,BorderLayout.NORTH)
  al = ParseListener(tf,tv,fr)
  pb.addActionListener(al)
  fr.pack()
  fr.setVisible(1)
예제 #2
0
    def onInfo(self, e):
        info = JFrame()
        info.setTitle("Info")
        info.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
        info.setSize(410, 400)
        info.setLocationRelativeTo(None)
        info.setResizable(False)
        info.setVisible(True)

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

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

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

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

        info.getContentPane().add(panel)
        info.add(panel)
예제 #3
0
    def bg(self, panel2, e):
        bground = JFrame()
        bground.setTitle("Change Background")
        bground.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE)
        bground.setSize(350, 100)
        bground.setLocationRelativeTo(None)
        bground.setVisible(True)
        bground.setResizable(False)

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

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

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

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

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

        bground.add(panel)
예제 #4
0
    def initResultados(self):
        diag = JFrame()
        self.lineas = list()
        self.areaResultados = JTextArea()
        numLineas = self.readResultados()

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

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

        #pane.getViewport().add(panelResultados)

        diag.setTitle("RESULTADOS OBTENIDOS")

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

        panelResultados.add(pane)
        diag.add(panelResultados, BorderLayout.CENTER)
예제 #5
0
class ConversationWindow(Conversation):
    """A GUI window of a conversation with a specific person"""
    def __init__(self, person, chatui):
        """ConversationWindow(basesupport.AbstractPerson:person)"""
        Conversation.__init__(self, person, chatui)
        self.mainframe = JFrame("Conversation with "+person.name)
        self.display = JTextArea(columns=100,
                                 rows=15,
                                 editable=0,
                                 lineWrap=1)
        self.typepad = JTextField()
        self.buildpane()
        self.lentext = 0

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

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

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

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

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

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

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

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

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

    def send(self, ae):
        text = self.typepad.getText()
        self.typepad.setText("")
        if text != "" and text != None:
            self.sendText(text)
예제 #6
0
class ConversationWindow(Conversation):
    """A GUI window of a conversation with a specific person"""
    def __init__(self, person, chatui):
        """ConversationWindow(basesupport.AbstractPerson:person)"""
        Conversation.__init__(self, person, chatui)
        self.mainframe = JFrame("Conversation with " + person.name)
        self.display = JTextArea(columns=100, rows=15, editable=0, lineWrap=1)
        self.typepad = JTextField()
        self.buildpane()
        self.lentext = 0

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

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

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

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

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

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

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

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

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

    def send(self, ae):
        text = self.typepad.getText()
        self.typepad.setText("")
        if text != "" and text != None:
            self.sendText(text)
예제 #7
0
    def show_pannel(self):
        # BP_STDOUT.println("Event code: %s" % self.contextMenuInvocation.getInputEvent())
        # self.scannerInstance.show_pannel.show()
        window = JFrame()
        window.setLayout(None)
        window.setTitle("Xcrpter")
        window.setSize(720, 540)
        window.setLocationRelativeTo(None)
        window.setResizable(True)
        window.setContentPane(self.scannerInstance.xpannel)
        window.setVisible(True)

        self.scannerInstance.xpannel.setPlain("")
        self.scannerInstance.xpannel.setVisible(True)
예제 #8
0
def geom_viewer(dsm2file = "dsm2.inp"):
  """
  geom_viewer(dsm2file = "dsm2.inp")
  starts off a dsm2 geometry viewer for dsm2 input data
  Irregular xsections are plotted if available otherwise
  regular xsections are plotted.
  """
  dgv = DSM2GeomViewer(dsm2file)
  mp = dgv.gui()
  fr = JFrame()
  fr.setTitle('Geom Viewer')
  fr.getContentPane().add(mp)
  fr.setLocation(300,100)
  fr.pack()
  sz = fr.getSize()
  fr.setSize(250,sz.height)
  fr.setVisible(1)
예제 #9
0
    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)
예제 #10
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)
예제 #11
0
class Image:
    """Holds an image of RGB pixels accessed by column and row indices (col, row).  
      Origin (0, 0) is at upper left."""

    # QUESTION:  For efficiency, should we also extract and save self.pixels (at image reading time)?
    # Also make setPixel(), getPixel(), setPixels() and getPixels() work on/with self.pixels.
    # And when writing, use code in current setPixels() to update image buffer, before writing it out?
    # This is something to try.

    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)

        # remember that this image has been created and is active (so that it can be stopped/terminated by JEM, if desired)
        _ActiveImages_.append(self)

    def getWidth(self):
        """Returns the width of the image."""

        return self.width

    def getHeight(self):
        """Returns the height of the image."""

        return self.height

    def getPixel(self, col, row):
        """Returns a list of the RGB values for this pixel, e.g., [255, 0, 0]."""

        # Obsolete - convert the row so that row zero refers to the bottom row of pixels.
        #row = self.height - row - 1

        color = Color(self.image.getRGB(col, row))  # get pixel's color
        return [color.getRed(),
                color.getGreen(),
                color.getBlue()]  # create list of RGB values (0-255)

    def setPixel(self, col, row, RGBlist):
        """Sets this pixel's RGB values, e.g., [255, 0, 0]."""

        # Obsolete - convert the row so that row zero refers to the bottom row of pixels.
        #row = self.height - row - 1

        color = Color(RGBlist[0], RGBlist[1],
                      RGBlist[2])  # create color from RGB values
        self.image.setRGB(col, row, color.getRGB())

    def getPixels(self):
        """Returns a 2D list of pixels (col, row) - each pixel is a list of RGB values, e.g., [255, 0, 0]."""

        pixels = []  # initialize list of pixels
        #for row in range(self.height-1, 0, -1):   # load pixels from image
        for row in range(0, self.height):  # load pixels from image
            pixels.append([])  # add another empty row
            for col in range(self.width):  # populate row with pixels
                # RGBlist = self.getPixel(col, row)   # this works also (but slower)
                color = Color(self.image.getRGB(col, row))  # get pixel's color
                RGBlist = [color.getRed(),
                           color.getGreen(),
                           color.getBlue()
                           ]  # create list of RGB values (0-255)
                pixels[-1].append(
                    RGBlist)  # add a pixel as (R, G, B) values (0-255, each)

        # now, 2D list of pixels has been created, so return it
        return pixels

    def setPixels(self, pixels):
        """Sets image to the provided 2D list of pixels (col, row) - each pixel is a list of RGB values, e.g., [255, 0, 0]."""

        self.height = len(pixels)  # get number of rows
        self.width = len(
            pixels[0]
        )  # get number of columns (assume all columns have same length

        #for row in range(self.height-1, 0, -1):   # iterate through all rows
        for row in range(0, self.height):  # iterate through all rows
            for col in range(
                    self.width):  # iterate through every column on this row

                RGBlist = pixels[row][col]
                #self.setPixel(col, row, RGBlist)   # this works also (but slower)
                color = Color(RGBlist[0], RGBlist[1],
                              RGBlist[2])  # create color from RGB values
                self.image.setRGB(col, row, color.getRGB())

    def read(self, filename):
        """Read an image from a .png, .gif, or .jpg file. as 2D list of RGB pixels."""

        # JEM working directory fix (see above)
        filename = fixWorkingDirForJEM(filename)  # does nothing if not in JEM

        # ***
        #print "fixWorkingDirForJEM( filename ) =", filename

        file = File(filename)  # read file from current directory
        self.image = ImageIO.read(file)
        self.width = self.image.getWidth(None)
        self.height = self.image.getHeight(None)

        pixels = []  # initialize list of pixels

        # load pixels from image
        for row in range(self.height):
            pixels.append([])  # add another empty row
            for col in range(self.width):  # now, populate row with pixels
                color = Color(self.image.getRGB(col, row))  # get pixel's color
                RGBlist = [color.getRed(),
                           color.getGreen(),
                           color.getBlue()
                           ]  # create list of RGB values (0-255)
                pixels[-1].append(
                    RGBlist)  # add a pixel as (R, G, B) values (0-255, each)

        # now, pixels have been loaded from image file, so create an image
        self.setPixels(pixels)

    def write(self, filename):
        """Saves the pixels to a file (.png or .jpg)."""

        # JEM working directory fix (see above)
        filename = fixWorkingDirForJEM(filename)  # does nothing if not in JEM

        # ***
        #print "fixWorkingDirForJEM( filename ) =", filename

        # get suffix
        suffix = filename[-3:]
        suffix = suffix.lower()

        if suffix == "jpg" or suffix == "png":
            ImageIO.write(self.image, suffix, File(filename))  # save, and also
            self.filename = filename  # update image filename
            self.display.setTitle(self.filename)  # update display title
        else:
            print "Filename must end in .jpg or .png"

    def show(self):
        """It displays the image."""

        self.display.setVisible(True)
        #self.display.repaint()          # draw it

    def hide(self):
        """It hides the image."""

        self.display.setVisible(False)
예제 #12
0
# Importing Java packages for simpler Java calls
from java.util import LinkedList, Arrays
python_list = [1, 2, 3]
java_list = LinkedList(Arrays.asList(1, 2, 3))
print str(type(python_list))
print str(type(java_list))

# Python adds helpful syntax to Java data structures
print python_list[0]
print java_list[0]   # can't normally do this in java
print java_list[0:2] # can't normally do this in java

# Iterate over Java collection the Python way
for entry in java_list:
    print entry

# "in" keyword compatibility
print str(3 in java_list)

# Create GUI with Java Swing
from javax.swing import JFrame
frame = JFrame() # don't call constructor with "new"
frame.setSize(400,400)
frame.setLocation(200, 200)
frame.setTitle("Jython JFrame")
frame.setVisible(True)

# Use JavaBean properties in constructor with keyword arguments!
JFrame(title="Super Jython JFrame", size=(400,400), visible=True)
예제 #13
0
class GroupConversationWindow(GroupConversation):
    """A GUI window of a conversation witha  group of people"""
    def __init__(self, group, chatui):
        GroupConversation.__init__(self, group, chatui)
        self.mainframe = JFrame(self.group.name)
        self.headers = ["Member"]
        self.memberdata = UneditableTableModel([], self.headers)
        self.display = JTextArea(columns=100, rows=15, editable=0, lineWrap=1)
        self.typepad = JTextField()
        self.buildpane()
        self.lentext = 0

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    def hidewindow(self, ae):
        self.hide()
예제 #15
0


start_file = ""
run_file = ""
directory = ""

#*****************
# Set Program locations, and include code
#*****************
CreateIcons = jmri.util.FileUtil.getExternalFilename('program:jython/DispatcherSystem/CreateIcons.py')
execfile(CreateIcons)

#*****************
frame = JFrame()
frame.setTitle("Dispatch System")
#frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) #comment as don't want to close down JMRI
frame.setSize(700, 550)

panel = JPanel()
panel.setLayout(BoxLayout(panel, BoxLayout.Y_AXIS))
frame.add(panel)

#*****Menu*******
bar = JMenuBar()
jmri.util.HelpUtil.helpMenu(bar, 'html.scripthelp.DispatcherSystem.DispatcherSystem' , True)
frame.setJMenuBar(bar)
#
logLevel = 0

###info
예제 #16
0
volumeIncreaseButton = JButton("Volume+", actionPerformed=doVolumeIncrease)
volumeDecreaseButton = JButton("Volume-", actionPerformed=doVolumeDecrease)
status = JTextField(preferredSize=(400, 20))

buttons = [
    openButton, rewindButton, stopButton, playButton, pauseButton,
    advanceButton, volumeIncreaseButton, volumeDecreaseButton
]
nbButtons = len(buttons)

win = JFrame("Music Player")
win.getContentPane().setLayout(FlowLayout())
for i in range(nbButtons):
    win.getContentPane().add(buttons[i])
win.getContentPane().add(status)
win.setTitle("Music Player")
win.setSize(700, 100)
win.setLocation(200, 100)
win.setVisible(True)
status.setText("Please open a WAV music file")
doDisplayTime = True

# Display loop
while (win.isVisible()):
    if player != None:
        if doDisplayTime:
            status.setText("Current time: " + getClipTime())
        else:
            status.setText("Current volume: " + str(volume))
            SoundPlayer.delay(300)
            doDisplayTime = True
예제 #17
0
파일: image.py 프로젝트: HenryStevens/jes
class Image:
   """Holds an image of RGB pixels accessed by column and row indices (col, row).  
      Origin (0, 0) is at upper left."""
      
# QUESTION:  For efficiency, should we also extract and save self.pixels (at image reading time)?
# Also make setPixel(), getPixel(), setPixels() and getPixels() work on/with self.pixels.  
# And when writing, use code in current setPixels() to update image buffer, before writing it out?
# This is something to try.
   
   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 getWidth(self):
      """Returns the width of the image.""" 
      
      return self.width
      
   def getHeight(self):
      """Returns the height of the image.""" 
      
      return self.height
      
   def getPixel(self, col, row):
      """Returns a list of the RGB values for this pixel, e.g., [255, 0, 0].""" 
      
      # Obsolete - convert the row so that row zero refers to the bottom row of pixels.
      #row = self.height - row - 1

      color = Color(self.image.getRGB(col, row))  # get pixel's color
      return [color.getRed(), color.getGreen(), color.getBlue()]  # create list of RGB values (0-255)

   def setPixel(self, col, row, RGBlist):
      """Sets this pixel's RGB values, e.g., [255, 0, 0].""" 
      
      # Obsolete - convert the row so that row zero refers to the bottom row of pixels.
      #row = self.height - row - 1

      color = Color(RGBlist[0], RGBlist[1], RGBlist[2])  # create color from RGB values
      self.image.setRGB(col, row, color.getRGB())


   def getPixels(self):
      """Returns a 2D list of pixels (col, row) - each pixel is a list of RGB values, e.g., [255, 0, 0].""" 
      
      pixels = []                      # initialize list of pixels
      #for row in range(self.height-1, 0, -1):   # load pixels from image      
      for row in range(0, self.height):   # load pixels from image      
         pixels.append( [] )              # add another empty row
         for col in range(self.width):    # populate row with pixels    
            # RGBlist = self.getPixel(col, row)   # this works also (but slower)    
            color = Color(self.image.getRGB(col, row))  # get pixel's color
            RGBlist = [color.getRed(), color.getGreen(), color.getBlue()]  # create list of RGB values (0-255)
            pixels[-1].append( RGBlist )   # add a pixel as (R, G, B) values (0-255, each)

      # now, 2D list of pixels has been created, so return it
      return pixels

   def setPixels(self, pixels):
      """Sets image to the provided 2D list of pixels (col, row) - each pixel is a list of RGB values, e.g., [255, 0, 0].""" 
      
      self.height = len(pixels)        # get number of rows
      self.width  = len(pixels[0])     # get number of columns (assume all columns have same length
      
      #for row in range(self.height-1, 0, -1):   # iterate through all rows      
      for row in range(0, self.height):   # iterate through all rows     
         for col in range(self.width):    # iterate through every column on this row
         
            RGBlist = pixels[row][col]
            #self.setPixel(col, row, RGBlist)   # this works also (but slower)
            color = Color(RGBlist[0], RGBlist[1], RGBlist[2])  # create color from RGB values
            self.image.setRGB(col, row, color.getRGB())

   def read(self, filename): 
      """Read an image from a .png, .gif, or .jpg file. as 2D list of RGB pixels."""
      
      # JEM working directory fix (see above)
      filename = fixWorkingDirForJEM( filename )   # does nothing if not in JEM
	  
      # ***
      #print "fixWorkingDirForJEM( filename ) =", filename

      file = File(filename)    # read file from current directory
      self.image = ImageIO.read(file)
      self.width  = self.image.getWidth(None)
      self.height = self.image.getHeight(None)
      
      pixels = []   # initialize list of pixels
      
      # load pixels from image
      for row in range(self.height):
         pixels.append( [] )   # add another empty row
         for col in range(self.width):   # now, populate row with pixels
            color = Color(self.image.getRGB(col, row))  # get pixel's color
            RGBlist = [color.getRed(), color.getGreen(), color.getBlue()]  # create list of RGB values (0-255)
            pixels[-1].append( RGBlist )   # add a pixel as (R, G, B) values (0-255, each)

      # now, pixels have been loaded from image file, so create an image
      self.setPixels(pixels)
      
   def write(self, filename):
      """Saves the pixels to a file (.png or .jpg)."""
      
      # JEM working directory fix (see above)
      filename = fixWorkingDirForJEM( filename )   # does nothing if not in JEM
	  
      # ***
      #print "fixWorkingDirForJEM( filename ) =", filename

      # get suffix
      suffix = filename[-3:]   
      suffix = suffix.lower()
      
      if suffix == "jpg" or suffix =="png":
         ImageIO.write(self.image, suffix, File(filename))  # save, and also
         self.filename = filename               # update image filename
         self.display.setTitle(self.filename)   # update display title            
      else:
         print "Filename must end in .jpg or .png"

   def show(self):
      """It displays the image."""
      
      self.display.setVisible(True)
      #self.display.repaint()          # draw it

   def hide(self):
      """It hides the image."""
      
      self.display.setVisible(False)
class correctionTable(TextPanel):
    """A class that displays an imagePlus and a resultstable. Resultstable and imp are linked in such a 
     way that click on a table row shows the imps respective timeframe."""
    def __init__(self, cell, mF, title="Results"): # add mF?
        # Call constructor of superclass
        TextPanel.__init__(self)
        # pass menue for setting save active/inactive
        self.cell = cell
        self.mF = mF
        # Create a window to show the content in
        self.window = JFrame()
        self.window.add(self)
        self.window.setTitle(title)
        # Add event listeners for keyboard and mouse responsiveness
        
        self.addKeyListener(ListenToKey())
        self.addMouseListener(ListenToMouse())
        
        # TODO: unpacking info out of cell object should be done in cell object itself and accessible e. g. via getData()
        self.imp = self.openImp(self.cell.getMeasTifPath())
        csvFile = open(self.cell.getCsvPath())        
        lines = csvFile.readlines()
        heads = lines.pop(0)
        self.setColumnHeadings("Frame\tDistance\tAnaphase")
        self.XYZtable = []
        for line in lines:      # load file lines in textPanel.
            frame, timepoint, dist, ch0x, ch0y, ch0z, ch0vol, ch1x, ch1y, ch1z, ch1vol = line.split(",")
            self.append(frame + "\t" + dist + "\t" )
            self.XYZtable.append((ch0x, ch0y, ch0z, ch0vol, ch1x, ch1y, ch1z, ch1vol))
        self.setSelection(0,0) # int startline, int endline
        self.changeFrame()
        self.mF.setSaveInactive()
        self.requestFocus()

        self.window.setSize(Dimension(220, 600))
        x = int(self.imp.getWindow().getLocation().getX()) + int(self.imp.getWindow().getWidth()) + 10
        self.window.setLocation(x, int(self.imp.getWindow().getLocation().getY()) )
        self.window.show()

    # Methods implementing KeyAdapter and MouseListener
    #... no multiple inheritance for Java classes?
    

    # - - - - Event driven methods - - - -
    # ------------------------------------

    def changeFrame(self):
        if self.getSelectionEnd() >= 0:
            frame, dist, AOCol = self.getLine(self.getSelectionEnd()).split("\t")
            self.imp.setSlice(int(frame)+1)
    
    def setAnaphase(self):
        frame, Distance, x = self.getLine(self.getSelectionEnd()).split("\t")
        #set anaphase onset
        self.cell.setAnOn(frame)
        for i in range(self.getLineCount()):   # very unelegantly solved, but it works.
            blFr, blDist, blAOCol = self.getLine(i).split("\t")
            self.setLine(i, blFr + "\t" + blDist + "\t")
            frame, distance, AOCol = self.getLine(self.getSelectionEnd()).split("\t") # get old line
            self.setLine(self.getSelectionEnd(), frame + "\t" + distance + "\tX")
        # setFocus back to tw,tp
        self.mF.setSaveActive()
        print "Anaphase set to", self.cell.getAnOn()

    def delVal(self):
        frame, distance, AOCol = self.getLine(self.getSelectionEnd()).split("\t")
        self.setLine(self.getSelectionEnd(), frame + "\tNA" + "\t" + AOCol)

    # - other methods
    def openImp(self, path):
        imp = ImagePlus(path)  # open associated tif file
        imp.show()
        imp.getWindow().setLocationAndSize(280, 120, imp.getWidth()*4, imp.getHeight()*4) # int x, int y, int width, int height
        return imp

    def getImp(self):
        return self.imp

    def getXYZtable(self):
        return self.XYZtable
        
    def closeWindows(self):
        self.imp.close()
        WindowManager.removeWindow(self.window)
        self.window.dispose()