当我尝试向arraylist添加项目时出现错误,我不确定我做错了什么。
ArrayList<JButton> buttonList = new ArrayList<JButton>();
buttonList.add(button);
buttonList.add(button1);
buttonList.add(button2);
我得到的错误是:
Syntax error on token "button", VariableDeclaratorId expected after this token
Syntax error on token "button1", VariableDeclaratorId expected after this token
Syntax error on token "button2", VariableDeclaratorId expected after this token
完整代码;
public buttons {
JButton button = new JButton();
JButton button1 = new JButton();
JButton button2 = new JButton();
ArrayList<JButton> buttonList = new ArrayList<JButton>();
buttonList.add(button);
buttonList.add(button1);
buttonList.add(button2);
public static void main(String args[]) {
}
}
答案 0 :(得分:2)
问题是您无法直接在类定义中添加Java代码,而是将其添加到方法中。
移动这部分代码:
buttonList.add(button);
buttonList.add(button1);
buttonList.add(button2);
进入类构造函数:
public buttons() {
buttonList.add(button);
buttonList.add(button1);
buttonList.add(button2);
}
此外,如果在类构造函数中初始化这些变量会更好:
public buttons {
JButton button;
JButton button1 = new JButton();
JButton button2 = new JButton();
ArrayList<JButton> buttonList;
public buttons() {
button = new JButton();
button1 = new JButton();
button2 = new JButton();
buttonList = new ArrayList<JButton>();
//...
buttonList.add(button);
buttonList.add(button1);
buttonList.add(button2);
}
public static void main(String args[]){
}
}
答案 1 :(得分:1)
放入主方法
public static void main(String args[]){
JButton button = new JButton();
JButton button1 = new JButton();
JButton button2 = new JButton();
ArrayList<JButton> buttonList = new ArrayList<JButton>();
buttonList.add(button);
buttonList.add(button1);
buttonList.add(button2);
}
答案 2 :(得分:1)
或者,您也可以使用 实例初始化程序 ,如此代码中所示(请注意buttonList.add()语句周围的开始和结束括号):
public class Button {
JButton button = new JButton();
JButton button1 = new JButton();
JButton button2 = new JButton();
ArrayList<JButton> buttonList = new ArrayList<JButton>();
{
buttonList.add(button);
buttonList.add(button1);
buttonList.add(button2);
}
// rest of the code ...
}
答案 3 :(得分:0)
变量: 按钮,按钮1或按钮2 不存在
试
ArrayList<JButton> buttonList = new ArrayList<JButton>();
JButton button = new JButton();
buttonList.add(button);
JButton button1 = new JButton();
buttonList.add(button1);
JButton button2 = new JButton();
buttonList.add(button2);