Adding a ActionPerformed Array to a String Array
Before you guys ask, yes I've searched online for the answer, but everything I found just leaves a lil confuse and nothing is recent so asking in those forums won't really help.
My problems is this:
开发者_StackOverflow社区I have an array that holds my name for a menu.
String[] fontColor = new String[] {"Red", "Blue", "Green"};
for (int i = 0; i < fontColors.length; i++) {
JMenuItem fontC = new JMenuItem(fontColors[i]);
fontC.addActionListener(new fontColorAction());
changeFontColor.add(fontC);
}
Then I have an array that holds my color change in a class called fontColorAction
in that class I have another array that does the same thing as my string array except all thats in the statement is textarea.setForeground(colorArr[i]);
that will set the setForeground() in order, but now how do I successfully attact the action listner in my class to my menuItems?
my class looks like this
private class fontColorAction implements ActionListener {
Color[] colorArr - new Color[] {"Color.RED","Color.BLUE","Color.GREEN"};
public void actionPerformed(ActionEvent e){
for(i = 0; i < collorArr.length; i++){
textarea.setForeground(colorArr[i]);
}
}
}
You can add a color attribute to your action:
private class FontColorAction implements ActionListener {
private Color color;
public FontColorAction (Color color){
this.color = color;
}
public void actionPerformed(ActionEvent e){
textarea.setForeground(color);
}
}
And initialize the actions like this:
String[] fontColor = new String[] {"Red", "Blue", "Green"};
Color[] colorArr - new Color[] {"Color.RED","Color.BLUE","Color.GREEN"};
for (int i = 0; i < fontColors.length; i++) {
JMenuItem fontC = new JMenuItem(fontColors[i]);
fontC.addActionListener(new fontColorAction(colorArr [i));
changeFontColor.add(fontC);
}
Also, by convention java classes have their first letter in upper case ;)
The FontColorAction is listening to the actions on the muenu items. I think you problem is this loop:
for(i = 0; i < collorArr.length; i++){
textarea.setForeground(colorArr[i]);
}
Here you are just setting the color to Color.GREEN because is the last item on the array. If you declare i as a field it will work.
private class fontColorAction implements ActionListener {
Color[] colorArr = new Color[] {"Color.RED","Color.BLUE","Color.GREEN"};
private int colorIndex = 0;
public void actionPerformed(ActionEvent e){
textarea.setForeground(colorArr[colorIndex]);
colorIndex++;
if(colorIndex==colorArr.length){
colorIndex = 0;
}
}
}
精彩评论