我想在Java中創建簡單的GUI程序,我找不到適當的解決方案,錯誤不能引用在不同的方法中定義的內部類中的非最終變量。不能引用非最終變量
這是我的小代碼到目前爲止;
myPanel = new JPanel();
JButton myButton = new JButton("create buttons");
myButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int val = Integer.parseInt(textfield.getText());
for(int i = 0; i < val; i++) {
JButton button = new JButton("");
button.setText(String.valueOf(i));
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clickButton(i);
}
});
myPanel.add(button);
myPanel.revalidate();
}
}
});
也許我的方法是完全錯誤的。我想要做的是;我想創建一組按鈕,並說當用戶按下一個按鈕時,我想顯示一條消息,如「您按下了按鈕4」或「您按下了按鈕10」。