Friday, April 24, 2009

Wednesday April 29th: JN25, part three

Today we will keep this part of the class to a minimum: you will only need to add a JComboBox to the JPanel from yesterday, you know, the one with the slider in it. You will then use this JComboBox to determine the font of the text in the JTextArea. Here's how you do it:

A) Add a new "listener" at the end of the line that says "implements ActionListener, ChangeListener"
so that it reads implements ActionListener, ChangeListener, ItemListener

we need an itemlistener here because comboboxes are basically lists of items, in this case, font names

B) In the constructor, add the code for creating the JComboBox and its JLabel JUST BELOW WHERE YOU ADDED THE SLIDER AND ITS LABEL

Here is the code you add:
//add array elements to JComboBox
daFonts = new JComboBox(typeStyle);
daFonts.setSize(150,25);
//add itemlistener to combobox
daFonts.addItemListener(this);


setWordz.add(daFonts); //add combobox to panel
whatDaFont = new JLabel("Please Choose a Font",SwingConstants.CENTER);


whatDaFont.setSize(150,25);

setWordz.add(whatDaFont); //add JLabel for combobox to panel


C) As you might imagine, you have to add a new ItemListener method to handle the event of you choosing a new font from the list. Here it is, and please enter it just below the other one you made yesterday:

public void itemStateChanged(ItemEvent e)

{
//set String variable for font style to item chosen in combobox
whichFont = daFonts.getSelectedItem().toString();


ChangeDemWordz(); //call method set size and font of JTextAreas
}//end itemStateChanged


As you can see, you're setting a String variable equal to whatever has been chosen from the JComboBox, then calling the same method from yesterday to apply it to text that gets typed

See how easy?
Mr. L

No comments:

Post a Comment