gpt4 book ai didi

java - 如何从 JTextpane 中选定的文本获取样式?

转载 作者:行者123 更新时间:2023-11-30 03:16:57 25 4
gpt4 key购买 nike

从 JTextPane 的选定文本中获取粗体和斜体样式

int start = jTextpane.getSelectionStart();
int end = jTextpane.getSelectionEnd();
String selectedText = jTextpane.getSelectedText();

应用样式

StyledDocument doc = (StyledDocument) jTextpane.getDocument();
Style logicalStyle = doc.getLogicalStyle(jTextpane.getSelectionStart());
Element element = doc.getCharacterElement(start);
AttributeSet as = element.getAttributes();

检查文本是否为粗体和斜体

boolean isBold = StyleConstants.isBold(as) ? false : true;
boolean isItalic = StyleConstants.isItalic(as);
System.out.println("selected value is isItalic?"+isItalic);
System.out.println("selected value is isBold?"+isBold);

最佳答案

您可以使用下面的代码从 JTextpane 中选定的文本获取样式。

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.text.AttributeSet;
import javax.swing.*;
import javax.swing.text.*;

public class TesxtPane {

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
JFrame frame = new TextStyleTestFrame();
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
class TextStyleTestFrame extends JFrame {
private JButton btnStyle = new JButton("Bold");
private JTextPane textPane = new JTextPane();

public TextStyleTestFrame() {
super("TextPaneStyle Test");
textPane.setText("Smaple String");
this.add(textPane, BorderLayout.CENTER);
JPanel panel = new JPanel();
panel.add(btnStyle);
this.add(panel, BorderLayout.NORTH);
btnStyle.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
changeStyle();
}
});
}


private void changeStyle() {

//get selected text style
int start = textPane.getSelectionStart();
int end = textPane.getSelectionEnd();

if (start == end) {
return;
}
StyledDocument doc = (StyledDocument) textPane.getDocument();
Element element = doc.getCharacterElement(start);
AttributeSet as = element.getAttributes();
//apply a new style based on previous
MutableAttributeSet asNew = new SimpleAttributeSet(as.copyAttributes());
StyleConstants.setBold(asNew, !StyleConstants.isBold(as));
doc.setCharacterAttributes(start, textPane.getSelectedText().length(), asNew, true);
String text = (StyleConstants.isBold(as) ? "Cancel Bold" : "Bold");
btnStyle.setText(text);
boolean isBold = StyleConstants.isBold(as) ? false : true;
boolean isItalic = StyleConstants.isItalic(as);
System.out.println("selected value is isItalic?" + isItalic);
System.out.println("selected value is isBold?" + isBold);
}

}

关于java - 如何从 JTextpane 中选定的文本获取样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32347189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com