Establecer el tamaño de fuente del texto seleccionado en JEditorPane usando JComboBox

¿Cómo puedo configurar el tamaño de fuente del texto seleccionado en un JEditorPane (panel)? ¿Usando un JComboBox?

anteriormente usé:

toolbar.add(new StyledEditorKit.FontSizeAction("12", 12));

Pero no puedes simplemente tener cientos de botones.

preguntado el 30 de junio de 12 a las 16:06

Bueno... descubrí cómo obtener un int del JComboBox... ¿Alguna forma de establecer la fuente del texto seleccionado usando un INT? -

Encuentra una buena demostración: stackoverflow.com/questions/939109/… -

1 Respuestas

No conozco la forma canónica de hacer esto, pero en la experimentación, esto funciona:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Action;
import javax.swing.JComboBox;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Document;
import javax.swing.text.StyledDocument;
import javax.swing.text.StyledEditorKit;

public class EditorPaneFun extends JPanel {
   private static final Integer[] ITEMS = { 9, 10, 11, 12, 14, 16, 18, 20, 24,
         32 };
   private JEditorPane editorPane = new JEditorPane();
   private JComboBox<Integer> fontBox = new JComboBox<Integer>(ITEMS);
   private StyledDocument doc = new DefaultStyledDocument();
   private StyledEditorKit styledEditorKit = new StyledEditorKit();

   public EditorPaneFun() {
      editorPane.setDocument(doc);
      editorPane.setEditorKit(styledEditorKit);
      JScrollPane scrollpane = new JScrollPane(editorPane);
      scrollpane.setPreferredSize(new Dimension(500, 400));
      JPanel comboPanel = new JPanel();
      comboPanel.add(fontBox);

      setLayout(new BorderLayout());
      add(scrollpane, BorderLayout.CENTER);
      add(comboPanel, BorderLayout.SOUTH);

      Document doc = editorPane.getDocument();
      for (int i = 0; i < 20; i++) {
         int offset = doc.getLength();
         String str = "This is line number: " + i + "\n";
         try {
            doc.insertString(offset, str, null);
         } catch (BadLocationException e) {
            e.printStackTrace();
         }
      }

      fontBox.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            int size = (Integer) fontBox.getSelectedItem();
            Action fontAction = new StyledEditorKit.FontSizeAction(String
                  .valueOf(size), size);
            fontAction.actionPerformed(e);
         }
      });
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("EditorPaneFun");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new EditorPaneFun());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

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

Tenga en cuenta que esto solo funciona si el documento es un documento con estilo predeterminado y si el kit de edición es un kit de edición con estilo.

Respondido el 30 de junio de 12 a las 16:06

No, esto no es bueno. mejor usar setCharacterAttributes(...)... Aférrate. - Aerodeslizador lleno de anguilas

El problema con esto es el hecho de que no puede seleccionar texto y hacerlo, por lo que el tamaño de fuente no cambia... - Primm

Encontré una respuesta AQUÍ: stackoverflow.com/questions/939109/… - Primm

@user1332495: Establecer atributos no es Mal, pero Action es más flexible. Si ya existe una instancia, puede usarla en múltiples contextos o HACIA EL FUTURO el evento, como se muestra aquí. - basurero

¡Ah gracias! Estaba usando un método diferente. Sin embargo, mi PC falló y lo perdí todo, así que volví a mirar esto. Esto realmente funciona mejor/más simple. ¡Gracias! - Primm

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.