Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 975
Suma Avatar asked Nov 17 '25 14:11

Suma


1 Answers

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.
like image 144
Reimeus Avatar answered Nov 19 '25 06:11

Reimeus