对于从JTextPane中的任何偏移量获取样式感兴趣的读者,本文将提供您所需要的所有信息,并且为您提供关于C/C++结构体成员偏移量获取、HTML页面没有出现在JavaSwingJTextPane中、
对于从JTextPane中的任何偏移量获取样式感兴趣的读者,本文将提供您所需要的所有信息,并且为您提供关于C/C++ 结构体成员偏移量获取、HTML页面没有出现在Java Swing JTextPane中、Java JTextPane JScrollPane显示问题、java – JTextPane阻止在父JScrollPane中滚动的宝贵知识。
本文目录一览:- 从JTextPane中的任何偏移量获取样式
- C/C++ 结构体成员偏移量获取
- HTML页面没有出现在Java Swing JTextPane中
- Java JTextPane JScrollPane显示问题
- java – JTextPane阻止在父JScrollPane中滚动
从JTextPane中的任何偏移量获取样式
有没有一种方法可以获取Style
,样式名称,甚至可以将插入时我给文本的样式Style
在某个位置上甚至与之进行比较JTextPane
?因为我的目的,我创建的自定义JTextPane
,StyledDocument
和DocumentFilter
。因此,我可以选择Style
用于表示常规字母,并用于表示数字的另一种样式。我还具有切换按钮,该按钮在切换时设置DocumentFilter
为以不同的方式设置数字格式,而在未切换时不定期设置数字格式,因此最后您无法仅根据JTextPane''sgetText()
方法区分哪些数字受到了影响。因此,唯一的方法是比较具有常规和特殊数字样式作为常量的样式。我唯一需要提出的就是如何为每个角色获取样式。
我知道有一种JTextPane''s
方法可以从插入符号的位置获取AttributeSet,getCharacterAttributes()
但是我认为这对我的问题没有用。
是否需要包含代码示例?我认为很难想象。如果您要我,我会包括在内。
任何输入将不胜感激。谢谢!
答案1
小编典典尝试调用StyledDocument.getCharacterElement(pos)
以获得该位置的character元素,然后调用Element.getAttributes()
以获得其属性集。
在AttributeSet
包含风格,你可以检索使用所提供的方法StyleConstants
。
C/C++ 结构体成员偏移量获取
分析代码节选自 muduo.
以下代码通过 offsetof 获取 sin_family 在 sockaddr_in6 中的字段偏移量.
static_assert(offsetof(sockaddr_in6, sin6_family) == 0, "sin6_family offset 0");
需要注意:
offsetof 并非 C/C++ 标准,需要编译器内置支持.
以及针对的数据类型,尽量使 POD 类型数据 (可参考下面链接中的提示).
具体详情可参考:https://en.cppreference.com/w/cpp/types/offsetof
补充:检查 sin_family6 字段时发现其是通过宏拼接而成,颇为有趣,代码如下所示:
1 //拼接宏
2 #define __SOCKADDR_COMMON(sa_prefix) \
3 sa_family_t sa_prefix##family
4
5 //结构体定义
6 #if !__USE_KERNEL_IPV6_DEFS
7 /* Ditto, for IPv6. */
8 struct sockaddr_in6
9 {
10 __SOCKADDR_COMMON (sin6_);
11 in_port_t sin6_port; /* Transport layer port # */
12 uint32_t sin6_flowinfo; /* IPv6 flow information */
13 struct in6_addr sin6_addr; /* IPv6 address */
14 uint32_t sin6_scope_id; /* IPv6 scope-id */
15 };
16 #endif /* !__USE_KERNEL_IPV6_DEFS */
PS:
如果您觉得我的文章对您有帮助,可以扫码领取下红包,谢谢!
HTML页面没有出现在Java Swing JTextPane中
我的SSCCE:
import java.awt.*; import java.io.IOException; import java.net.*; import javax.swing.*; import javax.swing.text.*; import javax.swing.text.html.*; @SuppressWarnings("serial") public class TestStyledDoc2 extends JPanel { public static final String GETTY_FILE = "http://www.d.umn.edu/~rmaclin/" + "gettysburg-address.html"; private HTMLEditorKit htmlKit = new HTMLEditorKit(); private HTMLDocument htmlDocument = (HTMLDocument) htmlKit.createDefaultDocument(); private JTextPane htmlPane = new JTextPane(htmlDocument); public TestStyledDoc2() { JScrollPane scrollPane1 = new JScrollPane(htmlPane); try { htmlPane.setEditorKit(htmlKit); URL gettyUrl = new URL(GETTY_FILE); htmlKit.read(gettyUrl.openStream(),htmlDocument,0); System.out.println(htmlDocument.getText(0,htmlDocument.getLength())); } catch (MalformedURLException e) { e.printstacktrace(); } catch (IOException e) { e.printstacktrace(); } catch (BadLocationException e) { e.printstacktrace(); } scrollPane1.getViewport().setPreferredSize(new Dimension(400,400)); setLayout(new BorderLayout()); add(scrollPane1,BorderLayout.CENTER); } private static void createAndShowUI() { JFrame frame = new JFrame("TestStyledDoc"); frame.getContentPane().add(new TestStyledDoc2()); frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeto(null); frame.setVisible(true); } public static void main(String[] args) { java.awt.EventQueue.invokelater(new Runnable() { public void run() { createAndShowUI(); } }); } }
解决方法
htmlPane.setEditorKit(htmlKit); htmlPane.setDocument(htmlDocument);
或者从您的textpane中重新获取文档
htmlPane.setEditorKit(htmlKit); htmlDocument = (HTMLDocument) htmlPane.getDocument();
Java JTextPane JScrollPane显示问题
以下类实现了chatGUI。正常运行时,屏幕如下所示:
精美的ChatGUI
http://img21.imageshack.us/img21/7177/rightchat.jpg
当我输入较大长度的文本时,问题经常出现。50到100个字符的gui变得疯狂。聊天记录框如下所示缩小
图片http://img99.imageshack.us/img99/6962/errorgui.jpg。
关于什么原因的任何想法?
谢谢。
PS:下面的附加类是完整的代码。您可以复制它并在计算机上进行编译,以确切地了解我的意思。
注意:一旦GUI变得疯狂,那么如果我单击“清除”按钮,历史记录窗口将清除,并且GUI返回到再次正确显示。
package Sartre.Connect4;
import javax.swing.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.StyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleConstants;
import javax.swing.text.BadLocationException;
import java.io.BufferedOutputStream;
import javax.swing.text.html.HTMLEditorKit;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JFileChooser;
/**
* Chat form class
* @author iAmjad
*/
public class ChatGUI extends JDialog implements ActionListener {
/**
* Used to hold chat history data
*/
private JTextPane textPaneHistory = new JTextPane();
/**
* provides scrolling to chat history pane
*/
private JScrollPane scrollPaneHistory = new JScrollPane(textPaneHistory);
/**
* used to input local message to chat history
*/
private JTextPane textPaneHome = new JTextPane();
/**
* Provides scrolling to local chat pane
*/
private JScrollPane scrollPaneHomeText = new JScrollPane(textPaneHome);
/**
* JLabel acting as a statusbar
*/
private JLabel statusBar = new JLabel("Ready");
/**
* Button to clear chat history pane
*/
private JButton JBClear = new JButton("Clear");
/**
* Button to save chat history pane
*/
private JButton JBSave = new JButton("Save");
/**
* Holds contentPane
*/
private Container containerPane;
/**
* Layout GridBagLayout manager
*/
private GridBagLayout gridBagLayout = new GridBagLayout();
/**
* GridBagConstraints
*/
private GridBagConstraints constraints = new GridBagConstraints();
/**
* Constructor for ChatGUI
*/
public ChatGUI(){
setTitle("Chat");
// set up dialog icon
URL url = getClass().getResource("Resources/SartreIcon.jpg");
ImageIcon imageIcon = new ImageIcon(url);
Image image = imageIcon.getImage();
this.setIconImage(image);
this.setAlwaysOnTop(true);
setLocationRelativeTo(this.getParent());
//////////////// End icon and placement /////////////////////////
// Get pane and set layout manager
containerPane = getContentPane();
containerPane.setLayout(gridBagLayout);
/////////////////////////////////////////////////////////////
//////////////// Begin Chat History //////////////////////////////
textPaneHistory.setToolTipText("Chat History Window");
textPaneHistory.setEditable(false);
textPaneHistory.setPreferredSize(new Dimension(350,250));
scrollPaneHistory.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPaneHistory.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
// fill Chat History GridBagConstraints
constraints.gridx = 0;
constraints.gridy = 0;
constraints.gridwidth = 10;
constraints.gridheight = 10;
constraints.weightx = 100;
constraints.weighty = 100;
constraints.fill = GridBagConstraints.BOTH;
constraints.anchor = GridBagConstraints.CENTER;
constraints.insets = new Insets(10,10,10);
constraints.ipadx = 0;
constraints.ipady = 0;
gridBagLayout.setConstraints(scrollPaneHistory,constraints);
// add to the pane
containerPane.add(scrollPaneHistory);
/////////////////////////////// End Chat History ///////////////////////
///////////////////////// Begin Home Chat //////////////////////////////
textPaneHome.setToolTipText("Home Chat Message Window");
textPaneHome.setPreferredSize(new Dimension(200,50));
textPaneHome.addKeyListener(new MyKeyAdapter());
scrollPaneHomeText.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPaneHomeText.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
// fill Chat History GridBagConstraints
constraints.gridx = 0;
constraints.gridy = 10;
constraints.gridwidth = 6;
constraints.gridheight = 1;
constraints.weightx = 100;
constraints.weighty = 100;
constraints.fill = GridBagConstraints.BOTH;
constraints.anchor = GridBagConstraints.CENTER;
constraints.insets = new Insets(10,10);
constraints.ipadx = 0;
constraints.ipady = 0;
gridBagLayout.setConstraints(scrollPaneHomeText,constraints);
// add to the pane
containerPane.add(scrollPaneHomeText);
////////////////////////// End Home Chat /////////////////////////
///////////////////////Begin Clear Chat History ////////////////////////
JBClear.setToolTipText("Clear Chat History");
// fill Chat History GridBagConstraints
constraints.gridx = 6;
constraints.gridy = 10;
constraints.gridwidth = 2;
constraints.gridheight = 1;
constraints.weightx = 100;
constraints.weighty = 100;
constraints.fill = GridBagConstraints.BOTH;
constraints.anchor = GridBagConstraints.CENTER;
constraints.insets = new Insets(10,10);
constraints.ipadx = 0;
constraints.ipady = 0;
gridBagLayout.setConstraints(JBClear,constraints);
JBClear.addActionListener(this);
// add to the pane
containerPane.add(JBClear);
///////////////// End Clear Chat History ////////////////////////
/////////////// Begin Save Chat History //////////////////////////
JBSave.setToolTipText("Save Chat History");
constraints.gridx = 8;
constraints.gridy = 10;
constraints.gridwidth = 2;
constraints.gridheight = 1;
constraints.weightx = 100;
constraints.weighty = 100;
constraints.fill = GridBagConstraints.BOTH;
constraints.anchor = GridBagConstraints.CENTER;
constraints.insets = new Insets(10,10);
constraints.ipadx = 0;
constraints.ipady = 0;
gridBagLayout.setConstraints(JBSave,constraints);
JBSave.addActionListener(this);
// add to the pane
containerPane.add(JBSave);
///////////////////// End Save Chat History /////////////////////
/////////////////// Begin Status Bar /////////////////////////////
constraints.gridx = 0;
constraints.gridy = 11;
constraints.gridwidth = 10;
constraints.gridheight = 1;
constraints.weightx = 100;
constraints.weighty = 50;
constraints.fill = GridBagConstraints.BOTH;
constraints.anchor = GridBagConstraints.CENTER;
constraints.insets = new Insets(0,5,0);
constraints.ipadx = 0;
constraints.ipady = 0;
gridBagLayout.setConstraints(statusBar,constraints);
// add to the pane
containerPane.add(statusBar);
////////////// End Status Bar ////////////////////////////
// set resizable to false
this.setResizable(false);
// pack the GUI
pack();
}
/**
* Deals with necessary menu click events
* @param event
*/
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
// Process Clear button event
if (source == JBClear){
textPaneHistory.setText(null);
statusBar.setText("Chat History Cleared");
}
// Process Save button event
if (source == JBSave){
// process only if there is data in history pane
if (textPaneHistory.getText().length() > 0){
// process location where to save the chat history file
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(false);
chooser.setAcceptAllFileFilterUsed(false);
FileNameExtensionFilter filter = new FileNameExtensionFilter("HTML Documents","htm","html");
chooser.setFileFilter(filter);
int option = chooser.showSaveDialog(ChatGUI.this);
if (option == JFileChooser.APPROVE_OPTION) {
// Set up document to be parsed as HTML
StyledDocument doc = (StyledDocument)textPaneHistory.getDocument();
HTMLEditorKit kit = new HTMLEditorKit();
BufferedOutputStream out;
try {
// add final file name and extension
String filePath = chooser.getSelectedFile().getAbsoluteFile() + ".html";
out = new BufferedOutputStream(new FileOutputStream(filePath));
// write out the HTML document
kit.write(out,doc,doc.getStartPosition().getOffset(),doc.getLength());
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(ChatGUI.this,"Application will now close. \n A restart may cure the error!\n\n"
+ e.getMessage(),"Fatal Error",JOptionPane.WARNING_MESSAGE,null);
System.exit(2);
} catch (IOException e){
JOptionPane.showMessageDialog(ChatGUI.this,null);
System.exit(3);
} catch (BadLocationException e){
JOptionPane.showMessageDialog(ChatGUI.this,null);
System.exit(4);
}
statusBar.setText("Chat History Saved");
}
}
}
}
/**
* Process return key for sending the message
*/
private class MyKeyAdapter extends KeyAdapter {
@Override
@SuppressWarnings("static-access")
public void keyPressed(KeyEvent ke) {
//DateTime dateTime = new DateTime();
//String nowdateTime = dateTime.getDateTime();
int kc = ke.getKeyCode();
if (kc == ke.VK_ENTER) {
try {
// Process only if there is data
if (textPaneHome.getText().length() > 0){
// Add message origin formatting
StyledDocument doc = (StyledDocument)textPaneHistory.getDocument();
Style style = doc.addStyle("HomeStyle",null);
StyleConstants.setBold(style,true);
String home = "Home [" + nowdateTime + "]: ";
doc.insertString(doc.getLength(),home,style);
StyleConstants.setBold(style,false);
doc.insertString(doc.getLength(),textPaneHome.getText() + "\n",style);
// update caret location
textPaneHistory.setCaretPosition(doc.getLength());
textPaneHome.setText(null);
statusBar.setText("Message Sent");
}
} catch (BadLocationException e) {
JOptionPane.showMessageDialog(ChatGUI.this,"Application will now close. \n A restart may cure the error!\n\n"
+ e.getMessage(),null);
System.exit(1);
}
ke.consume();
}
}
}
}
java – JTextPane阻止在父JScrollPane中滚动
JPanel JScrollPane JPanel JPanel JScrollPane JTextPane
当使用鼠标滚轮滚动外部JScrollPane我遇到一个恼人的问题.一旦鼠标光标触及内部JScrollPane,似乎滚动事件就会传递到JScrollPane中,并且第一个不再处理.这意味着滚动“父”JScrollPane停止.
是否可以仅禁用内部JScrollPane上的鼠标滚轮?或者更好的是,如果没有要滚动的内容(大多数情况下textpane只包含1-3行文本),则禁用滚动,但如果有更多内容则启用它?
解决方法
这个课就是这样做的.只需使用它代替常规的JScrollPane即可.我希望它对你有所帮助.
/** * A JScrollPane that will bubble a mouse wheel scroll event to the parent * JScrollPane if one exists when this scrollpane either tops out or bottoms out. */ public class PDControlScrollPane extends JScrollPane { public PDControlScrollPane() { super(); addMouseWheelListener(new PDMouseWheelListener()); } class PDMouseWheelListener implements MouseWheelListener { private JScrollBar bar; private int prevIoUsValue = 0; private JScrollPane parentScrollPane; private JScrollPane getParentScrollPane() { if (parentScrollPane == null) { Component parent = getParent(); while (!(parent instanceof JScrollPane) && parent != null) { parent = parent.getParent(); } parentScrollPane = (JScrollPane)parent; } return parentScrollPane; } public PDMouseWheelListener() { bar = PDControlScrollPane.this.getVerticalScrollBar(); } public void mouseWheelMoved(MouseWheelEvent e) { JScrollPane parent = getParentScrollPane(); if (parent != null) { /* * Only dispatch if we have reached top/bottom on prevIoUs scroll */ if (e.getWheelRotation() < 0) { if (bar.getValue() == 0 && prevIoUsValue == 0) { parent.dispatchEvent(cloneEvent(e)); } } else { if (bar.getValue() == getMax() && prevIoUsValue == getMax()) { parent.dispatchEvent(cloneEvent(e)); } } prevIoUsValue = bar.getValue(); } /* * If parent scrollpane doesn't exist,remove this as a listener. * We have to defer this till Now (vs doing it in constructor) * because in the constructor this item has no parent yet. */ else { PDControlScrollPane.this.removeMouseWheelListener(this); } } private int getMax() { return bar.getMaximum() - bar.getVisibleAmount(); } private MouseWheelEvent cloneEvent(MouseWheelEvent e) { return new MouseWheelEvent(getParentScrollPane(),e.getID(),e .getWhen(),e.getModifiers(),1,e .getClickCount(),false,e.getScrollType(),e .getScrollAmount(),e.getWheelRotation()); } } }
今天关于从JTextPane中的任何偏移量获取样式的讲解已经结束,谢谢您的阅读,如果想了解更多关于C/C++ 结构体成员偏移量获取、HTML页面没有出现在Java Swing JTextPane中、Java JTextPane JScrollPane显示问题、java – JTextPane阻止在父JScrollPane中滚动的相关知识,请在本站搜索。
本文标签: