简体   繁体   中英

Get font size of selected text in JTextPane

In my text editor, I give the option to change text through a JComboBox and a StyledEditorKit. The only problem is that once I select a size in the combo box (and it changes the selected text), and then select a new selection of text, the value in the combo box stays the same as the previous selection, regardless of the actual size.

I saw this post, but I don't really understand the given answer.

Here's the code I use to change the font

JComboBox<?> fontSizeCombo = new JComboBox<Object>(sizes.toArray());
fontSizeCombo.setFocusable(false);
fontSizeCombo.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
          new StyledEditorKit.FontSizeAction("myaction-", (int) ((JComboBox<?>) e.getSource()).getSelectedItem()).actionPerformed(e);
      }
});

"sizes" just contains ints ranging from 8 to 112 by increments of 4.

Any help is greatly appreciated.

The mentioned post means you should add a CaretListener to your editor. When sselection is changed caret position updates and the listener is invoked. Then InputAttributes of the kit is updated. You can access the attributes and get font size for current caret position (selection).

将插入号侦听器添加到您的文本窗格,该窗格调用组合框的更新。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM