本文整理汇总了Python中javax.swing.JTextPane.setCaretPosition方法的典型用法代码示例。如果您正苦于以下问题:Python JTextPane.setCaretPosition方法的具体用法?Python JTextPane.setCaretPosition怎么用?Python JTextPane.setCaretPosition使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.swing.JTextPane
的用法示例。
在下文中一共展示了JTextPane.setCaretPosition方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: OutputPane
# 需要导入模块: from javax.swing import JTextPane [as 别名]
# 或者: from javax.swing.JTextPane import setCaretPosition [as 别名]
class OutputPane(object):
"""Pane for outpout of interactive session"""
def __init__(self):
self.textpane = JTextPane()
self.doc = self.textpane.getStyledDocument()
self.textpane.editable = False
style_context = StyleContext.getDefaultStyleContext()
default_style = style_context.getStyle(StyleContext.DEFAULT_STYLE)
parent_style = self.doc.addStyle("parent", default_style)
StyleConstants.setFontFamily(parent_style, "Monospaced")
input_style = self.doc.addStyle("input", parent_style)
output_style = self.doc.addStyle("output", parent_style)
StyleConstants.setForeground(output_style, awtColor.BLUE)
error_style = self.doc.addStyle("error", parent_style)
StyleConstants.setForeground(error_style, awtColor.RED)
# Do a dance to set tab size
font = Font("Monospaced", Font.PLAIN, 12)
self.textpane.setFont(font)
fm = self.textpane.getFontMetrics(font)
tabw = float(fm.stringWidth(" "*4))
tabs = [
TabStop(tabw*i, TabStop.ALIGN_LEFT, TabStop.LEAD_NONE)
for i in xrange(1, 51)
]
attr_set = style_context.addAttribute(
SimpleAttributeSet.EMPTY,
StyleConstants.TabSet,
TabSet(tabs)
)
self.textpane.setParagraphAttributes(attr_set, False)
#Dance done!
def addtext(self, text, style="input", ensure_newline=False):
doclen = self.doc.length
if ensure_newline and doclen:
if self.doc.getText(doclen - 1, 1) != '\n':
text = '\n' + text
self.doc.insertString(self.doc.length, text, self.doc.getStyle(style))
# Scroll down
self.textpane.setCaretPosition(self.doc.length)
def clear(self):
"""Remove all text"""
self.doc.remove(0, self.doc.length)
示例2: OutputPane
# 需要导入模块: from javax.swing import JTextPane [as 别名]
# 或者: from javax.swing.JTextPane import setCaretPosition [as 别名]
class OutputPane(object):
def __init__(self):
self.textpane = JTextPane()
self.doc = self.textpane.getStyledDocument()
self.textpane.editable = False
default_style = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE)
parent_style = self.doc.addStyle("parent", default_style)
StyleConstants.setFontFamily(parent_style, "Monospaced")
input_style = self.doc.addStyle("input", parent_style)
output_style = self.doc.addStyle("output", parent_style)
StyleConstants.setForeground(output_style, Color.BLUE)
error_style = self.doc.addStyle("error", parent_style)
StyleConstants.setForeground(error_style, Color.RED)
def addtext(self, text, style="input", ensure_newline=False):
doclen = self.doc.length
if ensure_newline and self.doc.getText(doclen - 1, 1) != '\n':
text = '\n' + text
self.doc.insertString(self.doc.length, text, self.doc.getStyle(style))
# Scroll down
self.textpane.setCaretPosition(self.doc.length)
示例3: __init__
# 需要导入模块: from javax.swing import JTextPane [as 别名]
# 或者: from javax.swing.JTextPane import setCaretPosition [as 别名]
class Console:
PROMPT = sys.ps1
PROCESS = sys.ps2
BANNER = ["Jython Completion Shell", InteractiveConsole.getDefaultBanner()]
include_single_underscore_methods = False
include_double_underscore_methods = False
def __init__(self, namespace=None):
"""
Create a Jython Console.
namespace is an optional and should be a dictionary or Map
"""
self.history = History(self)
if namespace != None:
self.locals = namespace
else:
self.locals = {}
self.buffer = [] # buffer for multi-line commands
self.interp = Interpreter(self, self.locals)
sys.stdout = StdOutRedirector(self)
self.text_pane = JTextPane(keyTyped = self.keyTyped, keyPressed = self.keyPressed)
self.__initKeyMap()
self.doc = self.text_pane.document
self.__propertiesChanged()
self.__inittext()
self.initialLocation = self.doc.createPosition(self.doc.length-1)
# Don't pass frame to popups. JWindows with null owners are not focusable
# this fixes the focus problem on Win32, but make the mouse problem worse
self.popup = Popup(None, self.text_pane)
self.tip = Tip(None)
# get fontmetrics info so we can position the popup
metrics = self.text_pane.getFontMetrics(self.text_pane.getFont())
self.dotWidth = metrics.charWidth('.')
self.textHeight = metrics.getHeight()
# add some handles to our objects
self.locals['console'] = self
def insertText(self, text):
"""insert text at the current caret position"""
# seems like there should be a better way to do this....
# might be better as a method on the text component?
caretPosition = self.text_pane.getCaretPosition()
self.text_pane.select(caretPosition, caretPosition)
self.text_pane.replaceSelection(text)
self.text_pane.setCaretPosition(caretPosition + len(text))
def getText(self):
"""get text from last line of console"""
offsets = self.__lastLine()
text = self.doc.getText(offsets[0], offsets[1]-offsets[0])
return text.rstrip()
def getDisplayPoint(self):
"""Get the point where the popup window should be displayed"""
screenPoint = self.text_pane.getLocationOnScreen()
caretPoint = self.text_pane.caret.getMagicCaretPosition()
# BUG: sometimes caretPoint is None
# To duplicate type "java.aw" and hit '.' to complete selection while popup is visible
x = screenPoint.getX() + caretPoint.getX() + self.dotWidth
y = screenPoint.getY() + caretPoint.getY() + self.textHeight
return Point(int(x),int(y))
def hide(self, event=None):
"""Hide the popup or tip window if visible"""
if self.popup.visible:
self.popup.hide()
if self.tip.visible:
self.tip.hide()
def hideTip(self, event=None):
self.tip.hide()
self.insertText(')')
def showTip(self, event=None):
# get the display point before writing text
# otherwise magicCaretPosition is None
displayPoint = self.getDisplayPoint()
if self.popup.visible:
self.popup.hide()
line = self.getText()
self.insertText('(')
(name, argspec, tip) = jintrospect.getCallTipJava(line, self.locals)
if tip:
self.tip.showTip(tip, displayPoint)
#.........这里部分代码省略.........
示例4: Console
# 需要导入模块: from javax.swing import JTextPane [as 别名]
# 或者: from javax.swing.JTextPane import setCaretPosition [as 别名]
class Console(object):
PS1 = sys.ps1
PS2 = sys.ps2
def __init__(self, burp, namespace=None):
self.burp = burp
self.log = burp.log
self._locals = dict(Burp=burp)
self._buffer = []
self.history = History(self)
if namespace is not None:
self._locals.update(namespace)
self.interp = JythonInterpreter(self, self._locals)
self.textpane = JTextPane(keyTyped=self.keyTyped,
keyPressed=self.keyPressed)
self.textpane.setFont(Font('Monospaced', Font.PLAIN, 11))
self.burp.customizeUiComponent(self.textpane)
self.initKeyMap()
self.document.remove(0, self.document.getLength())
self.write('Burp Extender Jython Shell', prefix='')
self.write(self.PS1)
self.textpane.requestFocus()
burp.log.info('Interactive interpreter ready...')
@property
def document(self):
return self.textpane.document
def resetbuffer(self):
self._buffer = []
def keyTyped(self, event=None):
if not self.inLastLine():
event.consume()
def keyPressed(self, event):
if event.keyCode in (KeyEvent.VK_BACK_SPACE, KeyEvent.VK_LEFT):
self.backspaceListener(event)
def getText(self):
start, end = self.__getLastLineOffsets()
text = self.document.getText(start, end - start)
return text.rstrip()
def insertText(self, data):
position = self.textpane.getCaretPosition()
self.textpane.select(position, position)
self.textpane.replaceSelection(data)
self.textpane.setCaretPosition(position + len(data))
def replaceText(self, data):
start, end = self.__getLastLineOffsets()
self.textpane.select(start, end)
self.textpane.replaceSelection(data)
self.textpane.setCaretPosition(start + len(data))
def write(self, data, color=Color.black, prefix='\n'):
style = SimpleAttributeSet()
if color is not None:
style.addAttribute(StyleConstants.Foreground, color)
self.document.insertString(self.document.getLength(), prefix + data, style)
self.textpane.caretPosition = self.document.getLength()
def enterAction(self, event=None):
text = self.getText()
self._buffer.append(text)
source = '\n'.join(self._buffer)
more = self.interp.runsource(source)
if more:
self.write(self.PS2, color=Color.black)
else:
self.resetbuffer()
self.write(self.PS1)
self.history.append(text)
def deleteAction(self, event=None):
if self.inLastLine():
if self.textpane.getSelectedText():
self.document.remove(self.textpane.getSelectionStart(),
self.textpane.getSelectionEnd() - self.textpane.getSelectionStart())
elif self.textpane.getCaretPosition() < self.document.getLength():
self.document.remove(self.textpane.getCaretPosition(), 1)
def deleteEndLineAction(self, event=None):
if self.inLastLine():
position = self.textpane.getCaretPosition()
self.textpane.setSelectionStart(position)
_, end = self.__getLastLineOffsets()
#.........这里部分代码省略.........
示例5: ChatClient
# 需要导入模块: from javax.swing import JTextPane [as 别名]
# 或者: from javax.swing.JTextPane import setCaretPosition [as 别名]
#.........这里部分代码省略.........
## Event driven function to retrieve and send data to the server
def grabText(self, event):
'''Function to repeatedly grab new messages entered into the text
area and display them in the main text area. Resets the entry area
'''
# Grab the text from the text area
text=self.message.getText()
# Don't allow an empty string through
if text=='':
return
text=text.strip()
# Call the append text function
self.appendText('\nYou : '+text+'\n', self.username)
# Reset the text to be empty and grab focus so that it is ready for new text input
self.message.requestFocusInWindow()
self.message.setText('')
# Send the message to the server
data=text.encode()
self.tn.write(data+'\r\n')
## Function to handle appending of messages
def appendText(self, message, user=None):
'''This function takes care of appending any new messages to the content area
'''
message_label=JTextArea(message,2,3, font=self.label_2_font)
# If this is a message from the grab text function, create a new label, assign it's colours
if user!=None:
message_label.setBackground(Color(240,240,240))
message_label.setForeground(Color(129,129,129))
# Otherwise set the format for receive function (no user passed in)
else:
message_label.setBackground(Color(215,215,215))
message_label.setForeground(Color(40,153,153))
# Format and style options for the new message labels
message_label.setEditable(False)
message_label.setLineWrap(True)
message_label.setWrapStyleWord(True)
message_label.setBorder(BorderFactory.createLineBorder( Color(247,246,242),4))
# Sets the positioning of messages
self.main_content.setCaretPosition(self.main_content.getDocument().getLength())
doc = self.main_content.getStyledDocument()
attr=SimpleAttributeSet()
self.main_content.insertComponent(message_label)
# Essential for jtextarea to be able to stack message
doc.insertString( self.main_content.getDocument().getLength(),'\n ', attr)
# Not sure if needed
self.main_content.repaint()
### This is a late edit so it isn't included in the documentation. Basically trying to dynamically update the number
### of users label at runtime. Works for incrementing the value but not decrementing it.
print(message)
# Only split the message if there are enough values to split (greeting messages differ in format to chat messages)
try:
user, text=message.split(' : ')
except:
return
#print('Split values are %s %s'%(user, text))
user=str(user.strip())
#print(self.no_users)
#print(user+' : '+text)
# If the user already in the list, pass
if user in self.no_users:
if text == ('User %s amach sa teach !'%user):
self.no_users.remove(user)
print('User % removed'%user)
else:
#print('User %s not in list'%user)
if str(user) == 'You':
#print('User is equal to "You"')
return
self.no_users.append(user)
print('User appended')
self.number_users=len(self.no_users)
#print('Length of user list is '+str(self.number_users))
self.user_label2=JLabel(" Users online : %s "%str(len(self.no_users)),JLabel.RIGHT, font=self.label_2_font)
#print('Label created')
#print('Attempt to replace label')
self.client_layout.replace(self.user_label, self.user_label2)
self.user_label = self.user_label2
self.user_label.repaint()
self.user_label.revalidate()
print('Label updated')
## Function to control return button press in message field
def returnKeyPress(self,event):
'''This function creates an object for return key press when inside the message entry area,
creates an object of KeyAdapter and tests keycode for a match, responds with grab text callback
'''
key_object=Key()
key_value=key_object.keyPressed(event)
if key_value == 10:
self.grabText(event)