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
Rather than give you the solution outright, here are some guidelines to help you:
ActionListener (or even an Action), specifically add one to the JComboBox fontbox.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 exampleActionListener, read the value returned from getSelectedItem and call JTextField.setFont accordingly using the style constant from the object.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With