簡體   English   中英

在ActionPerformed上更改GridLayout中的JButton文本

[英]Changing JButton text in GridLayout on ActionPerformed

我試圖更改單擊時的JButton文本。 按鈕位於GridLayout中的數組中。 我嘗試使用.setText,但是NetBeans顯示錯誤。

從內部類引用的局部變量必須是final或有效的final

將變量從private更改為final並沒有幫助。 我是Java的新秀,如果有任何幫助,我將不勝感激。

   package widok;

   import java.awt.GridLayout;
   import java.awt.event.ActionEvent;
   import java.awt.event.ActionListener;
   import javax.swing.JButton;
   import javax.swing.JFrame;

   public class Gameplay extends JFrame {

private JButton[] button = new JButton[25];

public Gameplay() {

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    getContentPane().setLayout(new GridLayout(5, 5));

    for (int i = 0; i < 25; i++) {
        button[i] = new JButton(" ");

        button[i].addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent ae) {
                button[i].setText("X");
            }
        });

        getContentPane().add(button[i]);

    }

    pack();
    setVisible(true);

}

}

謝謝!

這里的問題是“ i”,它具有for循環的本地上下文,但是actionPerformed不在同一上下文中。 由於“ i”正在更改,因此無法將其定為最終值

您可以執行的操作會發出操作源,例如,可以從Actionaevent獲取操作源

        public void actionPerformed(ActionEvent ae) {
            JButton btn = (JButton)ae.getSource();
            btn.setText("X");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM