本文整理汇总了Python中javax.swing.JFrame.setLocationRelativeTo方法的典型用法代码示例。如果您正苦于以下问题:Python JFrame.setLocationRelativeTo方法的具体用法?Python JFrame.setLocationRelativeTo怎么用?Python JFrame.setLocationRelativeTo使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.swing.JFrame
的用法示例。
在下文中一共展示了JFrame.setLocationRelativeTo方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: Pipeline
# 需要导入模块: from javax.swing import JFrame [as 别名]
# 或者: from javax.swing.JFrame import setLocationRelativeTo [as 别名]
class Pipeline():
def __init__(self):
#If a swing interface is asked for this will be the JFrame.
self.frame = None
#Keeps track of the number of queries processed.
self.jobCount = 0
#Keeps track of the query currently being processed.
self.currentJob = ""
#Keeps track of the massage to be displayed.
self.message = 0
#Messages to be displayed at each stage in the processing of a single query.
self.messages = ["Searching for genes via genemark",
"Extending genes found via genemark",
"Searching for intergenic genes",
"Removing overlapping genes",
"Searching for promoters",
"Using transterm to find terminators",
"Removing transcription signals which conflict with genes",
"Using tRNAscan to find transfer RNAs",
"Writing Artemis file",
"Writing summary .xml, .html, and .xls files"]
self.exception = None
def initializeDisplay(self, queries, swing):
"""
queries: A list of the fasts files to be processed.
swing: If true then updates about progress will be displayed in a swing window, otherwise they will be written to stdout.
Initializes the interface for telling the user about progress in the pipeline. Queries is used to count the
number of queries the pipeline will process and to size the swing display(if it is used) so that text
isn't cutoff at the edge of the window. The swing display is setup if swing is true.
"""
self.numJobs = len(queries)
if swing:
self.frame = JFrame("Neofelis")
self.frame.addWindowListener(PipelineWindowAdapter(self))
contentPane = JPanel(GridBagLayout())
self.frame.setContentPane(contentPane)
self.globalLabel = JLabel(max(queries, key = len))
self.globalProgress = JProgressBar(0, self.numJobs)
self.currentLabel = JLabel(max(self.messages, key = len))
self.currentProgress = JProgressBar(0, len(self.messages))
self.doneButton = JButton(DoneAction(self.frame))
self.doneButton.setEnabled(False)
constraints = GridBagConstraints()
constraints.gridx, constraints.gridy = 0, 0
constraints.gridwidth, constraints.gridheight = 1, 1
constraints.weightx = 1
constraints.fill = GridBagConstraints.HORIZONTAL
contentPane.add(self.globalLabel, constraints)
constraints.gridy = 1
contentPane.add(self.globalProgress, constraints)
constraints.gridy = 2
contentPane.add(self.currentLabel, constraints)
constraints.gridy = 3
contentPane.add(self.currentProgress, constraints)
constraints.gridy = 4
constraints.weightx = 0
constraints.fill = GridBagConstraints.NONE
constraints.anchor = GridBagConstraints.LINE_END
contentPane.add(self.doneButton, constraints)
self.frame.pack()
self.frame.setResizable(False)
self.globalLabel.setText(" ")
self.currentLabel.setText(" ")
self.frame.setLocationRelativeTo(None)
self.frame.setVisible(True)
def updateProgress(self, job):
"""
query: Name of the query currently being processed.
This function use used for updating the progress shown in the interface. If job is not equal to currentJob then
global progress is incremented and shown and the currentProgress is reset and shown. If job is equal to currentJob
then the globalProgress does not change and currentProgress is increased.
"""
if self.exception:
raise self.exception
if self.frame:
if job != self.currentJob:
self.currentProgress.setValue(self.currentProgress.getMaximum())
self.globalLabel.setText(job)
self.globalProgress.setValue(self.jobCount)
print "Processing %s, %.2f%% done" % (job, 100.0*self.jobCount/self.numJobs)
self.jobCount += 1
self.currentJob = job
self.message = -1
self.message += 1
print " %s, %.2f%% done" % (self.messages[self.message], 100.0*self.message/len(self.messages))
self.currentProgress.setValue(self.message)
self.currentLabel.setText(self.messages[self.message])
else:
if job != self.currentJob:
print "Processing %s, %.2f%% done" % (job, 100.0*self.jobCount/self.numJobs)
self.jobCount += 1
#.........这里部分代码省略.........
示例2: JythonGui
# 需要导入模块: from javax.swing import JFrame [as 别名]
# 或者: from javax.swing.JFrame import setLocationRelativeTo [as 别名]
class JythonGui(object):
def __init__(self, instructionsURI=""):
self.instructionsURI = instructionsURI
self.logger = logging.getLogger("sasi_gridder_gui")
self.logger.addHandler(logging.StreamHandler())
def log_fn(msg):
self.log_msg(msg)
self.logger.addHandler(FnLogHandler(log_fn))
self.logger.setLevel(logging.DEBUG)
self.selected_input_file = None
self.selected_output_file = None
self.frame = JFrame("SASI Gridder", defaultCloseOperation=WindowConstants.EXIT_ON_CLOSE)
self.frame.size = (650, 600)
self.main_panel = JPanel()
self.main_panel.layout = BoxLayout(self.main_panel, BoxLayout.Y_AXIS)
self.frame.add(self.main_panel)
self.top_panel = JPanel(SpringLayout())
self.top_panel.alignmentX = Component.CENTER_ALIGNMENT
self.main_panel.add(self.top_panel)
self.stageCounter = 1
def getStageLabel(txt):
label = JLabel("%s. %s" % (self.stageCounter, txt))
self.stageCounter += 1
return label
# Instructions link.
self.top_panel.add(getStageLabel("Read the instructions:"))
instructionsButton = JButton(
('<HTML><FONT color="#000099">' "<U>open instructions</U></FONT><HTML>"),
actionPerformed=self.browseInstructions,
)
instructionsButton.setHorizontalAlignment(SwingConstants.LEFT)
instructionsButton.setBorderPainted(False)
instructionsButton.setOpaque(False)
instructionsButton.setBackground(Color.WHITE)
instructionsButton.setToolTipText(self.instructionsURI)
self.top_panel.add(instructionsButton)
# Select input elements.
self.top_panel.add(getStageLabel("Select an input data folder:"))
self.top_panel.add(JButton("Select input...", actionPerformed=self.openInputChooser))
# Select output elements.
self.top_panel.add(getStageLabel("Specify an output file:"))
self.top_panel.add(JButton("Specify output...", actionPerformed=self.openOutputChooser))
# Run elements.
self.top_panel.add(getStageLabel("Run SASI Gridder: (this might take a hwile"))
self.run_button = JButton("Run...", actionPerformed=self.runSASIGridder)
self.top_panel.add(self.run_button)
SpringUtilities.makeCompactGrid(self.top_panel, self.stageCounter - 1, 2, 6, 6, 6, 6)
# Progress bar.
self.progressBar = JProgressBar(0, 100)
self.main_panel.add(self.progressBar)
# Log panel.
self.log_panel = JPanel()
self.log_panel.alignmentX = Component.CENTER_ALIGNMENT
self.log_panel.setBorder(EmptyBorder(10, 10, 10, 10))
self.main_panel.add(self.log_panel)
self.log_panel.setLayout(BorderLayout())
self.log = JTextArea()
self.log.editable = False
self.logScrollPane = JScrollPane(self.log)
self.logScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
self.log_panel.add(self.logScrollPane, BorderLayout.CENTER)
# File selectors
self.inputChooser = JFileChooser()
self.inputChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES
self.outputChooser = JFileChooser()
self.outputChooser.fileSelectionMode = JFileChooser.FILES_ONLY
defaultOutputFile = os.path.join(System.getProperty("user.home"), "gridded_efforts.csv")
self.outputChooser.setSelectedFile(File(defaultOutputFile))
self.frame.setLocationRelativeTo(None)
self.frame.visible = True
def browseInstructions(self, event):
""" Open a browser to the instructions page. """
browseURI(self.instructionsURI)
return
def log_msg(self, msg):
self.log.append(msg + "\n")
self.log.setCaretPosition(self.log.getDocument().getLength())
def openInputChooser(self, event):
ret = self.inputChooser.showOpenDialog(self.frame)
#.........这里部分代码省略.........
示例3: JythonGui
# 需要导入模块: from javax.swing import JFrame [as 别名]
# 或者: from javax.swing.JFrame import setLocationRelativeTo [as 别名]
#.........这里部分代码省略.........
SpringUtilities.makeCompactGrid(
self.top_panel, self.stageCounter - 1, 2, 6, 6, 6, 6)
# Progress bar.
self.progressBar = JProgressBar(0, 100)
self.main_panel.add(self.progressBar)
# Log panel.
self.log_panel = JPanel()
self.log_panel.alignmentX = Component.CENTER_ALIGNMENT
self.log_panel.setBorder(EmptyBorder(10,10,10,10))
self.main_panel.add(self.log_panel)
self.log_panel.setLayout(BorderLayout())
self.log = JTextArea()
self.log.editable = False
self.logScrollPane = JScrollPane(self.log)
self.logScrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS)
self.logScrollBar = self.logScrollPane.getVerticalScrollBar()
self.log_panel.add(self.logScrollPane, BorderLayout.CENTER)
# File selectors
self.inputChooser = JFileChooser()
self.inputChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES
self.outputChooser = JFileChooser()
defaultOutputFile = os.path.join(System.getProperty("user.home"),
"sasi_project.zip")
self.outputChooser.setSelectedFile(File(defaultOutputFile));
self.outputChooser.fileSelectionMode = JFileChooser.FILES_ONLY
self.frame.setLocationRelativeTo(None)
self.frame.visible = True
def browseInstructions(self, event):
""" Open a browser to the instructions page. """
browseURI(self.instructionsURI)
def itemStateChanged(self, event):
""" Listen for checkbox changes. """
checkBox = event.getItemSelectable()
is_selected = (event.getStateChange() == ItemEvent.SELECTED)
result_field = self.resultFieldCheckBoxes[checkBox]
self.selected_result_fields[result_field['id']] = is_selected
def log_msg(self, msg):
""" Print message to log and scroll to bottom. """
self.log.append(msg + "\n")
self.log.setCaretPosition(self.log.getDocument().getLength())
def openInputChooser(self, event):
ret = self.inputChooser.showOpenDialog(self.frame)
if ret == JFileChooser.APPROVE_OPTION:
self.selected_input_file = self.inputChooser.selectedFile
self.log_msg("Selected '%s' as input." % self.selected_input_file.path)
def openOutputChooser(self, event):
ret = self.outputChooser.showSaveDialog(self.frame)
if ret == JFileChooser.APPROVE_OPTION:
selectedPath = self.outputChooser.selectedFile.path
if not selectedPath.endswith('.zip'):
zipPath = selectedPath + '.zip'
self.outputChooser.setSelectedFile(File(zipPath))
self.selected_output_file = self.outputChooser.selectedFile
示例4: getArguments
# 需要导入模块: from javax.swing import JFrame [as 别名]
# 或者: from javax.swing.JFrame import setLocationRelativeTo [as 别名]
#.........这里部分代码省略.........
constraints.gridx = 0
constraints.gridy = 0
constraints.gridwidth = 1
constraints.gridheight = 1
constraints.fill = GridBagConstraints.HORIZONTAL
constraints.weightx = 0
constraints.weighty = 0
contentPane.add(JLabel("Blast Location"), constraints)
constraints.gridy = 1
contentPane.add(JLabel("Genemark Location"), constraints)
constraints.gridy = 2
contentPane.add(JLabel("Transterm Location"), constraints)
constraints.gridy = 3
contentPane.add(JLabel("tRNAscan Location"), constraints)
constraints.gridy = 4
contentPane.add(JLabel("Databases Location"), constraints)
constraints.gridy = 5
contentPane.add(JLabel("Database"), constraints)
constraints.gridy = 6
contentPane.add(JLabel("Matrix(Leave blank to use heuristic matrix)"), constraints)
constraints.gridy = 7
contentPane.add(JLabel("E Value"), constraints)
constraints.gridy = 8
contentPane.add(JLabel("Minimum Intergenic Length"), constraints)
constraints.gridy = 9
contentPane.add(JLabel("Scaffold Distance"), constraints)
constraints.gridy = 10
contentPane.add(JLabel("Promoter Score Cutoff"), constraints)
constraints.gridy = 11
contentPane.add(JLabel("Query"), constraints)
constraints.gridx = 1
constraints.gridy = 0
constraints.weightx = 1
contentPane.add(blastField, constraints)
constraints.gridy = 1
contentPane.add(genemarkField, constraints)
constraints.gridy = 2
contentPane.add(transtermField, constraints)
constraints.gridy = 3
contentPane.add(tRNAscanField, constraints)
constraints.gridy = 4
contentPane.add(databaseLocationField, constraints)
constraints.gridy = 5
contentPane.add(databaseField, constraints)
constraints.gridy = 6
contentPane.add(matrixField, constraints)
constraints.gridy = 7
contentPane.add(eValueField, constraints)
constraints.gridy = 8
contentPane.add(minLengthField, constraints)
constraints.gridy = 9
contentPane.add(scaffoldingDistanceField, constraints)
constraints.gridy = 10
contentPane.add(promoterScoreField, constraints)
constraints.gridy = 11
contentPane.add(queryField, constraints)
constraints.gridx = 2
constraints.gridy = 0
constraints.weightx = 0
constraints.fill = GridBagConstraints.NONE
constraints.anchor = GridBagConstraints.LINE_END
contentPane.add(JButton(LocationAction(blastField)), constraints)
constraints.gridy = 1
contentPane.add(JButton(LocationAction(genemarkField)), constraints)
constraints.gridy = 2
contentPane.add(JButton(LocationAction(transtermField)), constraints)
constraints.gridy = 3
contentPane.add(JButton(LocationAction(tRNAscanField)), constraints)
constraints.gridy = 4
contentPane.add(JButton(LocationAction(databaseLocationField)), constraints)
constraints.gridy = 11
contentPane.add(JButton(LocationAction(queryField)), constraints)
constraints.gridx = 0
constraints.gridy = 12
constraints.anchor = GridBagConstraints.LINE_START
contentPane.add(JButton(HelpAction()), constraints)
constraints.gridx = 1
constraints.anchor = GridBagConstraints.LINE_END
contentPane.add(JButton(OKAction()), constraints)
constraints.gridx = 2
contentPane.add(JButton(CancelAction()), constraints)
frame.pack()
frame.setLocationRelativeTo(None)
frame.setVisible(True)
while frame.isVisible():
pass
self.blastLocation = blastField.getText()
self.genemarkLocation = genemarkField.getText()
self.transtermLocation = transtermField.getText()
self.database = databaseLocationField.getText() + "/" + databaseField.getText()
self.matrix = matrixField.getText()
self.eValue = float(eValueField.getText())
self.minLength = int(minLengthField.getText())
self.scaffoldingDistance = int(scaffoldingDistanceField.getText())
self.promoterScoreCutoff = float(promoterScoreField.getText())
self.sources = [queryField.getText()]
示例5: GraphicsWindow
# 需要导入模块: from javax.swing import JFrame [as 别名]
# 或者: from javax.swing.JFrame import setLocationRelativeTo [as 别名]
class GraphicsWindow(ActionListener, KeyListener, MouseInputListener):
"""
Creates a :py:class:`~jygsaw.graphicswindow.GraphicsWindow` with a
:py:class:`~jygsaw.graphicswindow.Canvas` object that can be drawn on.
Takes a title, window width, and window height.
An optional background color can be specified.
"""
colors = [BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN,
LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW]
def __init__(self, title, w, h, bg_color=WHITE):
assert w > 0, "GraphicsWindow width must be greater than zero"
assert h > 0, "GraphicsWindow height must be greater than zero"
self.objs = [] # List of GraphicsObjects
self.bg_color = bg_color
self.frame = JFrame(
title, defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
size=(w, h))
self.frame.setLocationRelativeTo(None)
self.frame.contentPane = Canvas(self, self.objs, self.bg_color)
self.frame.contentPane.setPreferredSize(Dimension(w, h))
self.frame.addMouseListener(self)
self.frame.addMouseMotionListener(self)
self.frame.addKeyListener(self)
# MouseEvent attributes
self.mouse_x = 0
self.mouse_y = 0
self.mouse_buttons = Set()
# Mouse callbacks
self.on_mouse_clicked = None
self.on_mouse_dragged = None
self.on_mouse_moved = None
self.on_mouse_pressed = None
self.on_mouse_released = None
self.on_mouse_exited = None
self.on_mouse_entered = None
# Key callbacks
self.on_key_pressed = None
self.on_key_released = None
self.on_key_typed = None
# Key values
self.last_key_char = None
self.last_key_code = None
self.chars_pressed = Set()
self.codes_pressed = Set()
# Event queue
self.event_queue = Queue()
self.main_running = False
# not needed, user_draw is called directly from on_draw
self.on_draw = None
def set_visible(self, visible):
"""Sets the window to visible."""
assert isinstance(visible, bool), "Variable is not a boolean."
self.frame.pack()
self.frame.visible = visible
def draw(self, *params):
"""
Takes any number of :py:class:`~jygsaw.graphicsobject.GraphicsObject`
or :py:class:`~jygsaw.shape.Shape` objects, or :py:class:`~jygsaw.group.Group`,
and draws them on the Canvas. If a shape is drawn without specifying a color
the default color is used. The default stroke option
(:py:class:`True` or :py:class:`False`) and *stroke_color* is saved in each object.
"""
for arg in params:
if isinstance(arg, GraphicsObject) or isinstance(arg, Shape):
if arg.color is None:
arg.color = self.frame.contentPane.default_color
arg.stroke_color = self.frame.contentPane.stroke_color
arg.stroke = self.frame.contentPane.stroke
arg.filled = self.frame.contentPane.filled
arg.stroke_width = self.frame.contentPane.stroke_width
if isinstance(arg, Text):
arg.font = self.frame.contentPane.font
arg.size = self.frame.contentPane.text_size
self.objs.append(arg)
elif isinstance(arg, Group):
for obj in arg.group:
if obj.color is None:
obj.color = self.frame.contentPane.default_color
obj.stroke_color = self.frame.contentPane.stroke_color
obj.stroke = self.frame.contentPane.stroke
obj.filled = self.frame.contentPane.filled
arg.stroke_width = self.frame.contentPane.stroke_width
if isinstance(arg, Text):
arg.font = self.frame.contentPane.font
arg.size = self.frame.contentPane.text_size
self.objs.append(obj)
#.........这里部分代码省略.........
示例6: JButton
# 需要导入模块: from javax.swing import JFrame [as 别名]
# 或者: from javax.swing.JFrame import setLocationRelativeTo [as 别名]
button = JButton("selected?", actionPerformed=click)
addButton = JButton("add 7", actionPerformed=add)
remButton = JButton("remove element", actionPerformed=rem)
chButton = JButton("Change to list B", actionPerformed=change)
listModel = DefaultListModel()
[listModel.addElement(e) for e in liste]
li = JList(listModel)
spane = JScrollPane(li) # making the list scrollable. li is now inside container JScrollPane
#b = JButton("press", actionPerformed=rem)
p.add(spane)
p.add(button)
p.add(addButton)
p.add(remButton)
p.add(chButton)
f.add(p)
f.pack()
f.setLocationRelativeTo(None)
f.setVisible(True)
print f.getParent()
print f.getLocationOnScreen()
print f.getContentPane().getSize()
示例7: __init__
# 需要导入模块: from javax.swing import JFrame [as 别名]
# 或者: from javax.swing.JFrame import setLocationRelativeTo [as 别名]
def __init__(self):
frame = JFrame("S1riu5 Spy")
frame.setSize(700, 690)
frame.setLocationRelativeTo(None);
frame.setLayout(BorderLayout())
tabPane = JTabbedPane(JTabbedPane.TOP)
#第一个Tab用来做C段查询
eachIp = self.getIp(HOSTDOMAIN)
iList = eachIp.split(".")
theIP = iList[0] + "." + iList[1] + "." + iList[2] + ".1/24"
panel1 = JPanel()
label = JLabel("IP CIDR:")
self.textfield1 = JTextField(theIP, 15)
button = JButton("SCAN", actionPerformed = self.cNmapScan)
self.textArea = JTextArea(40, 65)
self.textArea.append("IP: " + eachIp)
self.textArea.setLineWrap(True) #激活自动换行功能
self.textArea.setWrapStyleWord(True); # 激活断行不断字功能
panel1.add(label)
panel1.add(self.textfield1)
panel1.add(button)
panel1.add(JScrollPane(self.textArea)) #设置自动滚动条
tabPane.addTab("C segment query ", panel1)
#第二个Tab用来做子域名查询
theName = self.getDomain1(HOSTDOMAIN)
self.textArea2 = JTextArea(40, 65)
#self.textArea.append("IP: " + eachIp)
self.textArea2.setLineWrap(True) #激活自动换行功能
self.textArea2.setWrapStyleWord(True) # 激活断行不断字功能
label2 = JLabel("Domain: ")
self.textfield2 = JTextField(theName, 15)
button2 = JButton("SCAN", actionPerformed = self.subDomain)
self.panel2 = JPanel()
self.panel2.add(label2)
self.panel2.add(self.textfield2)
self.panel2.add(button2)
#self.panel2.add(scrollPane)
self.panel2.add(JScrollPane(self.textArea2))
tabPane.addTab("subDomains", self.panel2)
#第三个Tab用来做敏感文件扫描
self.tableData0 = [["1", "2"]]
colNames2 = ('url','http code')
dataModel3 = DefaultTableModel(self.tableData0, colNames2)
self.table3 = JTable(dataModel3)
##
label3 = JLabel("URL: ")
self.textfield3 = JTextField(HOSTDOMAIN, 15)
self.textArea3 = JTextArea(40, 65)
#self.textArea.append("IP: " + eachIp)
self.textArea3.setLineWrap(True) #激活自动换行功能
self.textArea3.setWrapStyleWord(True) # 激活断行不断字功能
a = 0
b = 0
self.label4 = JLabel(str(a) + "/" + str(b))
#
self.chkbox1 = JCheckBox('ASP')
self.chkbox2 = JCheckBox('ASPX')
self.chkbox3 = JCheckBox('JSP')
self.chkbox4 = JCheckBox('PHP')
self.chkbox5 = JCheckBox('MDB')
self.chkbox6 = JCheckBox('DIR')
button3 = JButton("SCAN", actionPerformed = self.senFileScan)
panel3 = JPanel()
panel3.add(label3)
panel3.add(self.textfield3)
panel3.add(self.chkbox1)
panel3.add(self.chkbox2)
panel3.add(self.chkbox3)
panel3.add(self.chkbox4)
panel3.add(self.chkbox5)
panel3.add(self.chkbox6)
panel3.add(button3)
panel3.add(self.label4)
panel3.add(JScrollPane(self.textArea3))
#.........这里部分代码省略.........
示例8: __init__
# 需要导入模块: from javax.swing import JFrame [as 别名]
# 或者: from javax.swing.JFrame import setLocationRelativeTo [as 别名]
class StackOverlay:
def __init__(self):
self.frame = None
self.overlayColorPreviewLabel = None
self.showStackOverlayWindow()
self.overlayColor = None
def onQuit(self, e):
print "Exiting..."
self.frame.dispose()
def showColorChooser(self, e):
colorChooser = JColorChooser()
self.overlayColor = colorChooser.showDialog(self.frame, "Choose color", Color.red)
self.overlayColorPreviewLabel.setBackground(self.overlayColor)
def showStackOverlayWindow(self):
all = JPanel()
all.setLayout(MigLayout())
self.imageIDs = WindowManager.getIDList()
self.imageNames = []
if self.imageIDs is None:
IJ.error("No open images", "Stack Overlay requires at least one image to be already open.")
return
for i in self.imageIDs:
self.imageNames.append(WindowManager.getImage(i).getTitle())
self.baseImageBox = JComboBox(self.imageNames)
baseImageBoxLabel = JLabel("Base image")
self.baseImageBox.setSelectedIndex(0)
all.add(baseImageBoxLabel)
all.add(self.baseImageBox, "wrap")
self.overlayImageBox = JComboBox(self.imageNames)
overlayImageBoxLabel = JLabel("Overlay image")
if len(self.imageNames) > 1:
self.overlayImageBox.setSelectedIndex(1)
all.add(overlayImageBoxLabel)
all.add(self.overlayImageBox, "wrap")
all.add(JSeparator(SwingConstants.HORIZONTAL), "span, wrap")
overlayStyleFrame = JPanel()
overlayStyleFrame.setLayout(MigLayout())
overlayStyleFrame.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Overlay Style"), BorderFactory.createEmptyBorder(5,5,5,5)))
colorLabel = JLabel("Overlay color")
self.overlayColorPreviewLabel = JLabel(" ")
self.overlayColorPreviewLabel.setBorder(BorderFactory.createEmptyBorder(0,0,1,0))
self.overlayColorPreviewLabel.setOpaque(True)
self.overlayColorPreviewLabel.setBackground(Color.red)
self.overlayColor = Color.red
colorPicker = JColorChooser()
colorPicker.setPreviewPanel(self.overlayColorPreviewLabel)
colorButton = JButton("Select color...", actionPerformed=self.showColorChooser)
opacityLabel = JLabel("Overlay opacity (%)")
opacitySpinnerModel = SpinnerNumberModel(100, 0, 100, 1)
self.opacitySpinner = JSpinner(opacitySpinnerModel)
overlayStyleFrame.add(colorLabel)
overlayStyleFrame.add(self.overlayColorPreviewLabel)
overlayStyleFrame.add(colorButton, "wrap")
overlayStyleFrame.add(opacityLabel)
overlayStyleFrame.add(self.opacitySpinner, "wrap")
all.add(overlayStyleFrame, "span, wrap")
self.virtualStackCheckbox = JCheckBox("Use Virtual Stack", True)
all.add(self.virtualStackCheckbox, "span, wrap")
# TODO: add non-thermonuclear cancel button functionality
overlayCancelButton = JButton("Cancel", actionPerformed=self.onQuit)
overlayStartButton = JButton("Overlay images", actionPerformed=self.overlayImages)
all.add(overlayCancelButton, "gapleft push")
all.add(overlayStartButton, "gapleft push")
self.frame = JFrame("Stack Overlay")
self.frame.getContentPane().add(JScrollPane(all))
self.frame.pack()
self.frame.setLocationRelativeTo(None)
self.frame.setVisible(True)
def overlayImages(self, e):
impBase = WindowManager.getImage(self.imageIDs[self.baseImageBox.getSelectedIndex()])
refBase = impBase.getStack().getProcessor(1)
impOverlay = WindowManager.getImage(self.imageIDs[self.overlayImageBox.getSelectedIndex()])
refOverlay = impOverlay.getStack().getProcessor(1)
print "Overlaying for stack sizes " + str(impBase.getStackSize()) + "/" + str(impOverlay.getStackSize()) + "..."
stack = None
#.........这里部分代码省略.........
示例9: GraphicsWindow
# 需要导入模块: from javax.swing import JFrame [as 别名]
# 或者: from javax.swing.JFrame import setLocationRelativeTo [as 别名]
class GraphicsWindow(ActionListener, KeyListener, MouseInputListener):
"""
Creates a :py:class:`~jygsaw.graphicswindow.GraphicsWindow` with a :py:class:`~jygsaw.graphicswindow.Canvas`
object that can be drawn on. Takes a title, window width, and window height.
An optional background color can be specified.
"""
def __init__(self, title, w, h, backgroundColor=white):
assert w > 0, "GraphicsWindow width must be greater than zero"
assert h > 0, "GraphicsWindow height must be greater than zero"
self._SHAPELIST_MAX_LENGTH = 200
self.objs = [] # List of GraphicsObjects
self.backgroundColor = backgroundColor
self.frame = JFrame(
title, defaultCloseOperation=JFrame.EXIT_ON_CLOSE,
size=(w, h))
self.frame.setLocationRelativeTo(None)
self.frame.contentPane = Canvas(self, self.objs, self.backgroundColor)
self.frame.contentPane.setPreferredSize(Dimension(w, h))
self.frame.addMouseListener(self)
self.frame.addMouseMotionListener(self)
self.frame.addKeyListener(self)
# MouseEvent attributes
self.mouseEventType = 0
self.mouseX = 0
self.mouseY = 0
# Mouse callbacks
self.onMouseClicked = None
self.onMouseDragged = None
self.onMouseMoved = None
self.onMousePressed = None
self.onMouseReleased = None
self.onMouseDragged = None
self.onMouseExited = None
self.onMouseEntered = None
# KeyEvent booleans keyPressed, keyTyped
self.keyEventType = 0
self.keyP = False
self.keyT = False
# Key callbacks
self.onKeyPressed = None
self.onKeyReleased = None
self.onKeyTyped = None
# Key values
self.lastKeyChar = None
self.lastKeyCode = None
self.charsPressed = Set()
# Event queue
self.eventQueue = Queue()
self.mainRunning = False
# not needed, user_draw is /called directly from onDraw
self.onDraw = None
def setVisible(self, isVisible):
"""Sets the window to visible."""
assert isinstance(isVisible, bool), "Variable is not a boolean."
self.frame.pack()
self.frame.visible = isVisible
def draw(self, *params):
"""
Takes any number of :py:class:`~jygsaw.graphicsobject.GraphicsObject`
or :py:class:`~jygsaw.shape.Shape` objects, or :py:class:`~jygsaw.group.Group`,
and draws them on the Canvas. If a shape is drawn without specifying a color
the default color is used. The default stroke option
(:py:class:`True` or :py:class:`False`) and *strokeColor* is saved in each object.
"""
for arg in params:
if isinstance(arg, GraphicsObject) or isinstance(arg, Shape):
if arg.color is None:
arg.color = self.frame.contentPane.defaultColor
arg.strokeColor = self.frame.contentPane.strokeColor
arg.stroke = self.frame.contentPane.stroke
arg.filled = self.frame.contentPane.filled
arg.strokeWidth = self.frame.contentPane.strokeWidth
if isinstance(arg, Text):
arg.font = self.frame.contentPane.font
arg.size = self.frame.contentPane.textSize
self.objs.append(arg)
if len(self.objs) > self._SHAPELIST_MAX_LENGTH:
warn("You have more than " + str(self._SHAPELIST_MAX_LENGTH) +
" to be drawn. You may want to add a clearHalf() call to your" +
" code to avoid slowing your system.")
elif isinstance(arg, Group):
for obj in arg.group:
#.........这里部分代码省略.........
示例10: Gui
# 需要导入模块: from javax.swing import JFrame [as 别名]
# 或者: from javax.swing.JFrame import setLocationRelativeTo [as 别名]
class Gui(MouseAdapter):
IMG_MIN_SIZE = 200
IMG_MAX_SIZE = 500
def __init__(self):
self.pos1 = None
self.puzzle = None
def mouseEntered(self, event):
self.in_canvas = True
def mouseExited(self, event):
self.in_canvas = False
def mouseReleased(self, event):
if not self.in_canvas or self.puzzle == None:
return
width = self.images_dict[0].getWidth()
height = self.images_dict[0].getHeight()
def valid_pos(pos):
return pos >= 0 and pos < self.puzzle.level()
x = (event.getX() - self.canvas.initial_x) / width
y = (event.getY() - self.canvas.initial_y) / height
if not valid_pos(x) or not valid_pos(y):
return
pos = Point(x, y)
if self.pos1 != None: #then is second click
if self.pos1.equals(pos):
self.pos1 = None
else:
self.play_event(self.pos1.y, self.pos1.x, pos.y, pos.x)
self.pos1 = None
else:
self.pos1 = pos
self.canvas.set_selected(self.pos1)
self.canvas.repaint()
def draw(self):
try:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
except:
pass
self.images_dict = dict()
self.canvas = Canvas(self.images_dict, None)
self.canvas.addMouseListener(self)
self.frame = JFrame("SimplePyzzle", visible = 1)
self.frame.setMinimumSize(Dimension(300, 300))
self.frame.setLocationRelativeTo(None)
self.generate_button = JButton("Generate Puzzle")
self.bottom_panel = JPanel()
self.combo_box_list = [9, 16, 25, 36, 49]
self.combo_box = JComboBox(self.combo_box_list)
self.frame.contentPane.add(self.canvas, BorderLayout.CENTER)
self.frame.contentPane.add(self.bottom_panel, BorderLayout.SOUTH)
self.bottom_panel.add(self.generate_button, BorderLayout.EAST)
self.bottom_panel.add(self.combo_box, BorderLayout.WEST)
self.generate_button.actionPerformed = self.generate_board
self.frame.setSize(500, 500)
self.frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE;
self.frame.pack()
def generate_board(self, event):
chooser = JFileChooser()
status = chooser.showOpenDialog(self.frame)
if status != JFileChooser.APPROVE_OPTION:
return
imageFile = chooser.getSelectedFile()
self.puzzle = SimplePyzzle(float(int(self.combo_box.getSelectedItem())))
self.draw_board()
self.load_images(imageFile, self.puzzle.level())
self.canvas.set_puzzle(self.puzzle)
width = self.images_dict[0].getWidth()
height = self.images_dict[0].getHeight()
size = Dimension(width * self.puzzle.level(), height * self.puzzle.level())
self.frame.setPreferredSize(size)
self.frame.setSize(size)
def show_error(self, error):
JOptionPane.showMessageDialog(self.frame, \
error, \
"Error!", \
JOptionPane.ERROR_MESSAGE)
def load_images(self, file, length):
#.........这里部分代码省略.........