Стили в JTextPane - Java
Формулировка задачи:
Как сделать что бы в JTextPane стиль и цвет менял только выделенный текст?
Листинг программы
- public static void main(String[] args){
- JFrame fr = new JFrame ("Блокнот");
- JTextPane txp = new JTextPane();
- fr.setSize (600,700);
- fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- fr.setLocationRelativeTo(null);
- fr.setVisible(true);
- fr.setLayout(new GridBagLayout());
- JMenuBar mb = new JMenuBar();
- fr.setJMenuBar(mb);
- JMenu mi4 = new JMenu("Шрифты");
- JMenuItem mc1 = new JMenuItem("Курсив");
- mc1.addActionListener(new ActionListener(){
- @Override
- public void actionPerformed(ActionEvent event) {
- txp.setFont(new Font ("", Font.ITALIC, 14));
- }
- });
Решение задачи: «Стили в JTextPane»
textual
Листинг программы
- private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
- // TODO add your handling code here:
- StyledDocument doc = (StyledDocument) jTextPane1.getDocument();
- int selectionEnd = jTextPane1.getSelectionEnd();
- int selectionStart = jTextPane1.getSelectionStart();
- if (selectionStart == selectionEnd) {
- return;
- }
- Element element = doc.getCharacterElement(selectionStart);
- AttributeSet as = element.getAttributes();
- MutableAttributeSet asNew = new SimpleAttributeSet(as.copyAttributes());
- StyleConstants.setBold(asNew, !StyleConstants.isBold(as));
- doc.setCharacterAttributes(selectionStart, jTextPane1.getSelectedText().length(), asNew, true);
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д