Reputation: 133
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
Reputation: 159794
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.Upvotes: 3
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