我正在尝试自动填充按钮的actionListener,但是我收到了错误 jObject = jArray.getJSONObject(i)generator()函数返回一个JSONArray。
我也想打印按钮[i] =新的JButton(" pfdfs"); as buttons [i] = new JButton(" i");
JButton b1= null, b2= null, b3= null, b4= null,b5 = null,b6= null,b7= null,b8= null,b9= null,b0= null;
JButton[] buttons = {b1, b2, b3, b4, b5,b6,b7,b8,b9,b0};
JSONArray jArray = generator();
//JSONObject jObject = null;
for (int i = 0; i <buttons.length;i++) {
buttons[i] = new JButton("pfdfs");
btnPnl.add(buttons[i]);
buttons[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//JSONObject jObject = null;
JSONObject jObject = null;
// jObject = null;
try {
jObject = jArray.getJSONObject(i);
我在这里得到了错误! jObject = jArray.getJSONObject(i);错误消息我在封闭范围内定义的局部变量必须是最终的或有效的最终
} catch (JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
String name = null;
try {
name= jObject.getString("Name");
} catch (JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
JLabel label2 = new JLabel();
label2.setText(pyetja);
label2.setFont(new Font("Arial", Font.PLAIN, 22));
name.removeAll();
name.repaint();
name.add(label2);
Image image = null;
String photoID = null;
try {
fotoID = jObject.getString("photoID");
} catch (JSONException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
File image2 = new File("D:\\photoFolder\\IMAGE ("+photoID+").jpg");
try {
image = ImageIO.read(image2);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
JLabel image= new JLabel(new ImageIcon(image));
Photo.removeAll();
Photo.repaint();
Photo.add(image);
try {
String test= jObject.getString("test");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
}
等待您的回复
答案 0 :(得分:0)
for (int i = 0; i <buttons.length;i++) {
final int k=i; //should create a final variable to get index.
buttons[i] = new JButton("pfdfs");
btnPnl.add(buttons[i]);
buttons[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//JSONObject jObject = null;
JSONObject jObject = null;
// jObject = null;
try {
jObject = jArray.getJSONObject(k);