下面列出了javax.swing.JTextPane#setCaretPosition ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void init() {
setLayout(new BorderLayout());
textPane = new JTextPane();
add(textPane,BorderLayout.CENTER);
manaPanel = new ManaPanel();
setPreferredSize(new Dimension(200, 150));
textPane.getDocument().putProperty(DefaultEditorKit.EndOfLineStringProperty, "\n");
translation=new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
int pos = textPane.getCaretPosition();
updateTextWithIcons();
textPane.setCaretPosition(pos);
}
};
}
/**
* Replace text.
*
* @param localNewText New text.
* @param localElement Element.
* @param localTextPane Text Pane.
*/
private void replace(
String localNewText,
Element localElement,
JTextPane localTextPane) {
if ((localElement == null) ||
(localTextPane == null) ||
(localNewText == null)) {
return;
}
// Initialize
int startOffset = MWPaneFormatter.getUUIDStartOffset(localTextPane, localElement);
int endOffset = MWPaneFormatter.getUUIDEndOffet(localTextPane, localElement);
// Replace
try {
localTextPane.getDocument().remove(startOffset, endOffset - startOffset);
localTextPane.getDocument().insertString(startOffset, localNewText, localElement.getAttributes());
localTextPane.setCaretPosition(startOffset);
localTextPane.moveCaretPosition(startOffset + localNewText.length());
} catch (BadLocationException e1) {
// Nothing to be done
}
}
/**
* Replace text.
*
* @param localNewText New text.
* @param localElement Element.
* @param localTextPane Text pane.
*/
private void replace(
String localNewText,
Element localElement,
JTextPane localTextPane) {
if ((localElement == null) ||
(localTextPane == null) ||
(localNewText == null)) {
return;
}
// Initialize
int startOffset = MWPaneFormatter.getUUIDStartOffset(localTextPane, localElement);
int endOffset = MWPaneFormatter.getUUIDEndOffet(localTextPane, localElement);
// Replace
try {
localTextPane.getDocument().remove(startOffset, endOffset - startOffset);
localTextPane.getDocument().insertString(startOffset, localNewText, localElement.getAttributes());
localTextPane.setCaretPosition(startOffset);
localTextPane.moveCaretPosition(startOffset + localNewText.length());
} catch (BadLocationException e1) {
// Nothing to be done
}
}
private JComponent buildContent() {
final JTextPane textPane = new JTextPane();
textPane.setEditable(false);
textPane.setContentType("text/html");
textPane.setText(parseVariables());
textPane.setCaretPosition(0);
final JScrollPane scrollPane = new JScrollPane(textPane,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
final JButton closeButton = new JButton(resourceBundle.getString("ui.dialog.markdown.button.close"));
closeButton.addActionListener(e -> SwingUtilities.invokeLater(this::closeDialog));
return FormBuilder.create()
.padding(new EmptyBorder(20, 20, 20, 20))
.columns("fill:200dlu:grow") //NON-NLS
.rows("fill:100dlu:grow, 10dlu, p") //NON-NLS
.add(scrollPane).xy(1, 1)
.addBar(closeButton).xy(1, 3, CellConstraints.RIGHT, CellConstraints.FILL)
.build();
}
public void updateHeadersPane(JTextPane pane) {
try {
updateTextPaneImpl(pane);
pane.setCaretPosition(0);
} catch (BadLocationException ex) {
Exceptions.printStackTrace(ex);
}
}
/**
* This helper method constructs a JTextPane with the given settings.
*/
private static JTextPane do_makeTextPane(boolean editable, int topMargin, int bottomMargin, int otherMargin) {
JTextPane x = OurAntiAlias.pane(null, Color.BLACK, Color.WHITE, new Font("Verdana", Font.PLAIN, 14));
x.setEditable(editable);
x.setAlignmentX(0);
x.setAlignmentY(0);
x.setCaretPosition(0);
x.setMargin(new Insets(topMargin, otherMargin, bottomMargin, otherMargin));
return x;
}
/**
* Replace link and displayed text.
*/
private void fullyReplace(
String localOldTitle,
String localNewTitle,
String localText,
Element localElement,
JTextPane localTextPane) {
if ((localElement != null) &&
(localTextPane != null) &&
(localNewTitle != null) &&
(localNewTitle.length() > 0)) {
localTextPane.setCaretPosition(MWPaneFormatter.getUUIDStartOffset(localTextPane, localElement));
localTextPane.moveCaretPosition(MWPaneFormatter.getUUIDEndOffet(localTextPane, localElement));
String newText = null;
if ((localText != null) &&
(localText.length() > 0) &&
(localNewTitle.length() > 0) &&
(localText.charAt(0) != localNewTitle.charAt(0)) &&
(Character.toUpperCase(localText.charAt(0)) == Character.toUpperCase(localNewTitle.charAt(0)))) {
newText = "[[" + localText.charAt(0) + localNewTitle.substring(1) + "]]";
} else {
newText = "[[" + localNewTitle + "]]";
}
localTextPane.replaceSelection(newText);
LinkReplacement.addLastReplacement(localOldTitle, localNewTitle);
}
}
@Override
protected JComponent getTextComponent(String locator) throws Exception {
JTextPane textComponent = new JTextPane();
textComponent.setText(getContent(locator));
textComponent.setFont(new Font("monospaced", Font.PLAIN, 12));
textComponent.setEditable(false);
textComponent.setCaretPosition(0);
textComponent.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
return textComponent;
}
protected JComponent getTextComponent(String locator) throws Exception {
JTextPane textComponent = new JTextPane();
textComponent.setText(getContent(locator));
textComponent.setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
textComponent.setEditable(false);
textComponent.setCaretPosition(0);
return textComponent;
}
public CancelOrderDialog(JFrame owner, Market market, AssetOrder order, ContractState state) {
super(owner, ModalityType.APPLICATION_MODAL);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setTitle(tr("canc_cancel_order"));
isToken = market.getTokenID()!=null;
this.market = market;
this.order = order;
this.state = state;
conditions = new JTextPane();
conditions.setContentType("text/html");
conditions.setPreferredSize(new Dimension(80, 160));
conditions.setEditable(false);
acceptBox = new JCheckBox(tr("dlg_accept_terms"));
// Create a button
JPanel buttonPane = new JPanel(new FlowLayout(FlowLayout.RIGHT));
pin = new JPasswordField(12);
pin.addActionListener(this);
calcelButton = new JButton(tr("dlg_cancel"));
okButton = new JButton(tr("dlg_ok"));
getRootPane().setDefaultButton(okButton);
calcelButton.addActionListener(this);
okButton.addActionListener(this);
if(Globals.getInstance().usingLedger()) {
ledgerStatus = new JTextField(26);
ledgerStatus.setEditable(false);
buttonPane.add(new Desc(tr("ledger_status"), ledgerStatus));
LedgerService.getInstance().setCallBack(this);
}
else
buttonPane.add(new Desc(tr("dlg_pin"), pin));
buttonPane.add(new Desc(" ", calcelButton));
buttonPane.add(new Desc(" ", okButton));
// set action listener on the button
JPanel content = (JPanel)getContentPane();
content.setBorder(new EmptyBorder(4, 4, 4, 4));
JPanel conditionsPanel = new JPanel(new BorderLayout());
conditionsPanel.setBorder(BorderFactory.createTitledBorder(tr("dlg_terms_and_conditions")));
conditionsPanel.add(new JScrollPane(conditions), BorderLayout.CENTER);
conditionsPanel.add(acceptBox, BorderLayout.PAGE_END);
JPanel centerPanel = new JPanel(new BorderLayout());
centerPanel.add(conditionsPanel, BorderLayout.PAGE_END);
content.add(centerPanel, BorderLayout.CENTER);
content.add(buttonPane, BorderLayout.PAGE_END);
suggestedFee = Globals.getInstance().getNS().suggestFee().blockingGet();
boolean isBuy = false;
if(order!=null && order.getType() == AssetOrder.OrderType.BID)
isBuy = true;
if(state!=null && state.getType() == ContractType.BUY)
isBuy = true;
StringBuilder terms = new StringBuilder();
terms.append(PlaceOrderDialog.HTML_STYLE);
terms.append("<h3>").append(tr("canc_terms_brief", isBuy ? tr("token_buy") : tr("token_sell"), market,
isToken ? order.getId() : state.getAddress().getRawAddress())).append("</h3>");
if(isToken) {
terms.append("<p>").append(tr("canc_terms_token",
NumberFormatting.BURST.format(suggestedFee.getPriorityFee().longValue()))).append("</p>");
}
else {
terms.append("<p>").append(tr("canc_terms_contract",
state.getBalance().toUnformattedString(),
NumberFormatting.BURST.format(state.getActivationFee() + suggestedFee.getPriorityFee().longValue()))
).append("</p>");
}
conditions.setText(terms.toString());
conditions.setCaretPosition(0);
pack();
}
@Override
protected Window createComponent() {
JDialog window = new JDialog(null, "Response to " + command, ModalityType.MODELESS);
window.setAlwaysOnTop(false);
window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
// TODO remember dimensions
window.setSize(800, 600);
installEscapeCloseOperation(window);
response = new JTextPane();
response.setEditable(false);
response.setContentType("text/html");
response.setText(text);
response.setCaretPosition(0);
scroller = new JScrollPane(this.response);
form = new FormView();
form.addField(
Fields
.textFieldBuilder()
.notEditable()
.labelled("Status")
.named("status")
.build()
);
form.addField(
Fields
.textFieldBuilder()
.notEditable()
.labelled("From")
.named("from")
.build()
);
form.addField(
Fields
.textFieldBuilder()
.notEditable()
.labelled("Type")
.named("type")
.build()
);
form.addField(
new JLabel("Attributes"),
scroller,
LabelLocation.TOP
);
window.add(form.getComponent());
return window;
}
JHTML(String s)
{
super(new BorderLayout());
html = new JTextPane();
html.setEditable(false); // need to set this explicitly to fix swing 1.3 bug
html.setCaretPosition(0);
html.setContentType("text/html");
// Enable posting of form submit events to the hyper link listener
final HTMLEditorKit htmlEditor
= (HTMLEditorKit)html.getEditorKitForContentType("text/html");
try {
// Call htmlEditor.setAutoFormSubmission(false); if available (Java 5+)
final Method setAutoFormSubmissionMethod = htmlEditor.getClass()
.getMethod("setAutoFormSubmission", new Class[]{ Boolean.TYPE});
setAutoFormSubmissionMethod.invoke(htmlEditor,
new Object[]{Boolean.FALSE});
} catch (final Throwable t) {
Activator.log.warn("Failed to enable auto form submission for JHTMLBundle.", t);
}
html.setText(s);
html.setCaretPosition(0);
html.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent ev)
{
if (ev.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
final URL url = ev.getURL();
try {
if (Util.isBundleLink(url)) {
final long bid = Util.bidFromURL(url);
Activator.disp.getBundleSelectionModel().clearSelection();
Activator.disp.getBundleSelectionModel().setSelected(bid, true);
} else if (Util.isImportLink(url)) {
JCMInfo.importCfg(JHTML.this);
} else {
Util.openExternalURL(url);
}
} catch (final Exception e) {
Activator.log.error("Failed to show " + url, e);
}
}
}
});
scroll =
new JScrollPane(html, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
html.setPreferredSize(new Dimension(300, 300));
add(scroll, BorderLayout.CENTER);
}
/**
* Replace text.
*
* @param localNewText New text.
* @param localElement Element.
* @param localTextPane Text pane.
*/
private void replace(
String localNewText,
Element localElement,
JTextPane localTextPane) {
if ((localElement == null) ||
(localTextPane == null) ||
(localNewText == null)) {
return;
}
// Text finalization
if (page != null) {
try {
PageAnalysis analysis = page.getAnalysis(localNewText, false);
List<PageElementFunction> functions = analysis.getFunctions();
boolean parseNeeded = false;
if (functions != null) {
for (PageElementFunction function : functions) {
if (function.getMagicWord() == null) {
parseNeeded = true;
} else if (!function.getMagicWord().isFunctionNotPSTMagicWord()) {
parseNeeded = true;
}
}
}
if (parseNeeded) {
API api = APIFactory.getAPI();
localNewText = api.parseText(page.getWikipedia(), page.getTitle(), localNewText, false);
}
} catch (APIException e) {
// Nothing to do
}
}
// Initialize
int startOffset = MWPaneFormatter.getUUIDStartOffset(localTextPane, localElement);
int endOffset = MWPaneFormatter.getUUIDEndOffet(localTextPane, localElement);
// Replace
try {
localTextPane.getDocument().remove(startOffset, endOffset - startOffset);
localTextPane.getDocument().insertString(startOffset, localNewText, localElement.getAttributes());
localTextPane.setCaretPosition(startOffset);
localTextPane.moveCaretPosition(startOffset + localNewText.length());
} catch (BadLocationException e1) {
// Nothing to be done
}
}
private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutMenuItemActionPerformed
String version = MainFrame.class.getPackage().getImplementationVersion();
if (version == null) {
version = "unknown";
}
JTextPane textPane = new JTextPane();
textPane.setEditable(false);
textPane.setContentType("text/html");
textPane.setText(
"<font face=sans-serif><strong><font size=+2>ProCamCalib</font></strong> version " + version + "<br>" +
"Copyright (C) 2009-2014 Samuel Audet <<a href=\"mailto:[email protected]%28Samuel%20Audet%29\">[email protected]</a>><br>" +
"Web site: <a href=\"http://www.ok.ctrl.titech.ac.jp/~saudet/procamcalib/\">http://www.ok.ctrl.titech.ac.jp/~saudet/procamcalib/</a><br>" +
"<br>" +
"Licensed under the GNU General Public License version 2 (GPLv2).<br>" +
"Please refer to LICENSE.txt or <a href=\"http://www.gnu.org/licenses/\">http://www.gnu.org/licenses/</a> for details."
);
textPane.setCaretPosition(0);
Dimension dim = textPane.getPreferredSize();
dim.height = dim.width*3/4;
textPane.setPreferredSize(dim);
textPane.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if(e.getEventType() == EventType.ACTIVATED) {
try {
Desktop.getDesktop().browse(e.getURL().toURI());
} catch(Exception ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE,
"Could not launch browser to \"" + e.getURL()+ "\"", ex);
}
}
}
});
// pass the scrollpane to the joptionpane.
JDialog dialog = new JOptionPane(textPane, JOptionPane.PLAIN_MESSAGE).
createDialog(this, "About");
if ("com.sun.java.swing.plaf.gtk.GTKLookAndFeel".equals(UIManager.getLookAndFeel().getClass().getName())) {
// under GTK, frameBackground is white, but rootPane color is OK...
// but under Windows, the rootPane's color is funny...
Color c = dialog.getRootPane().getBackground();
textPane.setBackground(new Color(c.getRGB()));
} else {
Color frameBackground = this.getBackground();
textPane.setBackground(frameBackground);
}
dialog.setVisible(true);
}
private void aboutMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aboutMenuItemActionPerformed
String version = MainFrame.class.getPackage().getImplementationVersion();
if (version == null) {
version = "unknown";
}
JTextPane textPane = new JTextPane();
textPane.setEditable(false);
textPane.setContentType("text/html");
textPane.setText(
"<font face=sans-serif><strong><font size=+2>ProCamTracker</font></strong> version " + version + "<br>" +
"Copyright (C) 2009-2014 Samuel Audet <<a href=\"mailto:[email protected]%28Samuel%20Audet%29\">[email protected]</a>><br>" +
"Web site: <a href=\"http://www.ok.ctrl.titech.ac.jp/~saudet/procamtracker/\">http://www.ok.ctrl.titech.ac.jp/~saudet/procamtracker/</a><br>" +
"<br>" +
"Licensed under the GNU General Public License version 2 (GPLv2).<br>" +
"Please refer to LICENSE.txt or <a href=\"http://www.gnu.org/licenses/\">http://www.gnu.org/licenses/</a> for details."
);
textPane.setCaretPosition(0);
Dimension dim = textPane.getPreferredSize();
dim.height = dim.width*3/4;
textPane.setPreferredSize(dim);
textPane.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if(e.getEventType() == EventType.ACTIVATED) {
try {
Desktop.getDesktop().browse(e.getURL().toURI());
} catch(Exception ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE,
"Could not launch browser to \"" + e.getURL()+ "\"", ex);
}
}
}
});
// pass the scrollpane to the joptionpane.
JDialog dialog = new JOptionPane(textPane, JOptionPane.PLAIN_MESSAGE).
createDialog(this, "About");
if ("com.sun.java.swing.plaf.gtk.GTKLookAndFeel".equals(UIManager.getLookAndFeel().getClass().getName())) {
// under GTK, frameBackground is white, but rootPane color is OK...
// but under Windows, the rootPane's color is funny...
Color c = dialog.getRootPane().getBackground();
textPane.setBackground(new Color(c.getRGB()));
} else {
Color frameBackground = this.getBackground();
textPane.setBackground(frameBackground);
}
dialog.setVisible(true);
}