2012-05-13 2 views
3

Я нахожу, что количество полезной документации/учебных пособий в Интернете не хватает, когда речь заходит о теме JTextPanes. Я пытаюсь сделать простой текстовый процессор, и я хочу, чтобы он мог выбрать семейство шрифтов из JComboBox, который заполняется на основе шрифтов, установленных пользователем в их системе. Однако, независимо от того, что я пытаюсь экспериментировать, я не могу понять, как заставить его работать.Как разрешить пользователю изменять свой шрифт в JTextPane с помощью JComboBox?

У меня есть класс панели инструментов, который построен на JTextPane. В настоящее время у него есть куча кнопок стиля, которые работают, чтобы установить выравнивание, полужирный, курсив и подчеркивание.

Вот мой код:

/** 
* The StyleBar is used to customize styles in a Styled Document. It will take a 
* JTextPane as an argument for its constructor and then all actions to be taken 
* will affect the text in it. 
* 
* @author Andrew 
*/ 
public class StyleBar extends JToolBar { 

    private JLabel fontLbl; 
    private JComboBox fontBox; 

     // ...Irrelevant stuff to the problem at hand. 

    /** 
    * The initEvents method is used to initialize the necessary events for the 
    * tool bar to actually do its job. It establishes the focus listener to the 
    * buttons on the bar, and gives each one its individual functionality. It 
    * also establishes the Font Selection interface. 
    */ 
    public void initEvents() { 
     //For each item in the tool bar, add the focus listener as well as the 
     //formatting listeners: 
     boldFormat.addActionListener(new StyledEditorKit.BoldAction()); //boldFormat is 
     boldFormat.addActionListener(resetFocus);      //a JButton 

     //Ditto for my italicsFormat and underlineFormat button(s) in the toolbar 

     leftAlign.addActionListener(new StyledEditorKit.AlignmentAction(null, 
       StyleConstants.ALIGN_LEFT)); 
     leftAlign.addActionListener(resetFocus); //This listener just resets focus 
                //back onto the TextPane. 

     //Ditto for my right and centerAlign buttons 

     //Set up the Font list, and add a listener to the combo box 
     buildFontMenu(); 
    } 

    /** 
    * The buildFontMenu detects all of the SYstem's available fonts and adds 
    * them to the Font Selection box. 
    */ 
    public void buildFontMenu(){ 
     GraphicsEnvironment ge = 
       GraphicsEnvironment.getLocalGraphicsEnvironment(); 
     final String[] fontNames = ge.getAvailableFontFamilyNames(); 
     for (int i = 0; i < fontNames.length; i++){ 
      //What do I do here to take the entry at String[i] and make it so that when 
      //the user selects it it sets the font Family in a similar way to that of 
      //pressing the boldFormat button or the leftAlign button? 
     } 
    } 

    //Everything else is irrelevant 

Так, чтобы подвести итог моей проблемы: я понятия не имею, как правильно установить слушатель в ComboBox, что а) он чувствителен к индивидуальному выбранному шрифту и б) какой-то образом использует StyledEditorKit.FontFamilyAction, чтобы сделать жизнь легкой?

Слэш, если я приближаюсь к чему-либо об этом неправильно, я бы хотел услышать правильный путь. Как я уже сказал, мои источники в Интернете не очень понятны по этому вопросу.

Большое спасибо!

ответ

3

StyledEditorTest ставит Action с в JToolBar, но идея такая же. См. Также Charles Bell's HTMLDocumentEditor, упомянутый here. Например,

bar.add(new StyledEditorKit.FontFamilyAction("Serif", Font.SERIF)); 
bar.add(new StyledEditorKit.FontFamilyAction("SansSerif", Font.SANS_SERIF)); 

Добавление: Как вы используете JComboBox, вы можете вперед событие к соответствующему StyledEditorKitAction, который работает от текущего выбора по умолчанию.

JComboBox combo = new JComboBox(); 
combo.addItem("Serif"); 
combo.addItem("Sans"); 
combo.addActionListener(new ActionListener() { 

    Action serif = new StyledEditorKit.FontFamilyAction("Serif", Font.SERIF); 
    Action sans = new StyledEditorKit.FontFamilyAction("Sans", Font.SANS_SERIF); 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     if ("Sans".equals(e.getActionCommand())) { 
      sans.actionPerformed(e); 
     } else { 
      serif.actionPerformed(e); 
     } 
    } 
}); 
0

Это может быть немного поздно, но я обнаружил, что застрял на аналогичной проблемой, и хотя предыдущий ответ не поможет, вот более полный ответ, когда вы хотите использовать все шрифты, доступные в компьютер ..

Где «шрифты» является массив строк, содержащий все нужные шрифты, которые будут использоваться в программе

 final JComboBox jcb = new JComboBox(fonts); 

    final Action [] actions = new Action[fonts.length]; 

    for (int i = 0; i < actions.length; i++) 
    { 
     actions[i] = new StyledEditorKit.FontFamilyAction(fonts[i], fonts[i]); 
    } 

    jcb.addActionListener(new ActionListener() 
     { 
      public void actionPerformed(ActionEvent event) 
      { 
       for (int i = 0; i < actions.length; i++) 
       { 
        if (fonts[i].equals((String)jcb.getSelectedItem())) 
        { 
         actions[i].actionPerformed(event); 
         break; 
        } 
       } 
      } 
     }); 
Смежные вопросы