问候,我正在尝试这样做:
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));
但没有效果。
--- ---- EDIT 我觉得有些人对我想要的东西感到困惑:
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)
答案 0 :(得分:2)
您使用同名
定义了两个不同的变量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)
答案 1 :(得分:1)
你应该学习Java的基础知识,因为你的代码有重大的基本问题(浮动a不能在那里公开定义,除非它真的在别的地方,你只是把它放在那里向我们展示)。您不能为变量定义两次相同的名称;调用一个fuentMenu和一个fuentString或其他。