Suma
Suma

Reputation: 133

Change text font using menu

I have this code that when user click on one of the fonts "bold or italic..." the text should change. I couldn't add the action listener that will do that:

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class question4 extends JFrame {

    private JTextField textField;
    private JComboBox fontbox;
    private String names[]={ "Bold","Italic","Plain"};
    private Icon icons[]={};


    public question4()
    {
        super("JcheckBox");
        setLayout(new FlowLayout());//set frame
        fontbox = new JComboBox(names);//set jcobobox
        fontbox.setMaximumRowCount(3);
        //listener

        add(fontbox);
        //add the text content
        textField = new JTextField ("Hello World", 20);
        textField.setFont(new Font("Calibri", Font.BOLD,18));//set the text font and size
        add(textField);//add textfield to jframe
    }

    public static void main(String args[])
    {
        question4 obj = new question4();//create object
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        obj.setSize(700,400);
        obj.setVisible(true);
    }//end main

 }//end class

Upvotes: 3

Views: 3855

Answers (2)

Reimeus
Reimeus

Reputation: 159794

Rather than give you the solution outright, here are some guidelines to help you:

  • Revisit the notion of an ActionListener (or even an Action), specifically add one to the JComboBox fontbox.
  • Create a JComboBox custom object for your Font styles so as to wrap both the text displayed and the integer constant to be used (hint). As a guide, see this example
  • Then in your ActionListener, read the value returned from getSelectedItem and call JTextField.setFont accordingly using the style constant from the object.

Upvotes: 3

Alya'a Gamal
Alya'a Gamal

Reputation: 5638

You need to add ActionListner to FontBox (JcomboBox) Like this:

  private void fontboxActionPerformed(java.awt.event.ActionEvent evt) {
    String font = (String) fontbox.getSelectedItem();

    if(font=="Bold")
        textField.setFont(new Font("Calibri", Font.BOLD, 18));
    else if(font == "Italic")
        textField.setFont(new Font("Calibri", Font.ITALIC, 18));
    else if(font == "Plain")
        textField.setFont(new Font("Calibri", Font.PLAIN, 18));

}

And call this method in your code like this:

fontbox.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        fontboxActionPerformed(evt);
    }
});

Upvotes: 0

Related Questions