public class buttonInitialization extends JFrame {
public JButton[] button;
public buttonInitialization() {
setLayout(new FlowLayout());
JButton[] button = new JButton[2];
button[0] = new JButton("");
button[0].setText("dsadsa");
button[0].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
button[0].setText("dsaadsdsa");
}
我无法在动作侦听器中访问此button[0]
。我怎么能这样做?
答案 0 :(得分:0)
制作button
变量final
。
final JButton[] button = new JButton[2];
这是一个要求,因为匿名内部类(如new ActionListener()
)只有在final
时才能访问外部类变量。
编辑我尝试编译并且可以正常工作。再来一次:
final JButton[] button = new JButton[2];
button[0] = new JButton("");
button[0].setText("dsadsa");
button[0].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
button[0].setText("dsaadsdsa");
}
});
答案 1 :(得分:0)
public class buttonInitialization extends JFrame {
public JButton[] button;
public buttonInitialization() {
setLayout(new FlowLayout());
JButton[] button = new JButton[2];
button[0] = new JButton("");
button[0].setText("dsadsa");
for(int i = 0; i< button.length; ++i)
button[i].addActionListener(new MyActionListener(button[i]));
}
private class MyActionListener implements ActionListener
{
private JButton button;
public MyActionListener(JButton button)
{
this.button = button;
}
@Override
public void actionPerformed(ActionEvent arg0) {
this.button.setText("dsaadsdsa");
}
}