您好,我正在尝试这样做:
public float a=0;
for(a=1 ; a<100;a++){
String fuent="font"+String.valueOf((int)a);
JMenuItem fuent=new JMenuItem(String.valueOf(a));
fuent.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){texto.setFont(texto.getFont().deriveFont(a)); current=a;}});
tamano.add(fuent);
}
但它会抛出这些错误:
cambiar.java:71: error: variable fuent is already defined in constructor cambiar()
JMenuItem fuent=new JMenuItem(String.valueOf(a));
^
cambiar.java:72: error: cannot find symbol
fuent.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){texto.setFont(texto.getFont().deriveFont(a)); current=a;}});
^
symbol: method addActionListener(<anonymous ActionListener>)
location: variable fuent of type String
2 errors
[Finished in 0.5s with exit code 1]
我正在尝试这样做:
JMenuItem (String)fuent=new JMenuItem(String.valueOf(a));
JMenuItem System.out.println(fuent)=new JMenuItem(String.valueOf(a));
但没有任何效果。
---编辑---- 我认为有些人对我想要的东西感到困惑:
String fuent="font"+String.valueOf((int)a);
JMenuItem fuent=new JMenuItem(String.valueOf(a));//(Here sould go the value of the String, Example "font1")
fuent.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){texto.setFont(texto.getFont().deriveFont(a)); current=a;}});
tamano.add(fuent); //(Same Here)
最佳答案
您定义了两个具有相同名称的不同变量
String fuent ="font"+String.valueOf((int)a);
JMenuItem fuent =new JMenuItem(String.valueOf(a));
例如,尝试重命名其中一个或两个
String strFuent="font"+String.valueOf((int)a);
JMenuItem miFuent=new JMenuItem(String.valueOf(a));
更新示例
JMenuItem fuent=new JMenuItem("font"+String.valueOf((int)a));
解决你的问题
OP编辑后更新
这仍然行不通...
String fuent="font"+String.valueOf((int)a); // You have defined fuent as a String
// Here you are trying to define fuent AGAIN as a JMenuItem
// You CAN NOT DO THIS...
// Change one of the variable names
JMenuItem fuent=new JMenuItem(String.valueOf(a));//(Here sould go the value of the String, Example "font1")
fuent.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){texto.setFont(texto.getFont().deriveFont(a)); current=a;}});
tamano.add(fuent); //(Same Here)
这现在可以工作了...
String fuent1="font"+String.valueOf((int)a); // You have defined fuent as a String
JMenuItem fuent=new JMenuItem(fuent1);
fuent.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
texto.setFont(texto.getFont().deriveFont(a)); current=a;
}
});
tamano.add(fuent); //(Same Here)
关于java - 在 for 循环中创建 JMenuitem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12223196/