如何在代碼中調用一個按鈕來執行操作?我知道要使用動作偵聽器,但如果按鈕沒有如下所示的變量名稱呢?如何調用按鈕在我的代碼中執行操作?
我是Java新手,請耐心等待。
public class Game
{
public static void main (String[] args)
{
JFrame frame = new JFrame ("Game");
frame.setLayout(new GridLayout(7, 6));
for(int i = 0; i < 42; i++)
{
frame.add(new JButton()); // This is the part I'm talking about!!!
}
frame.getContentPane().add(new gameBoard());
frame.pack();
frame.setVisible(true);
}
謝謝。
通常按鈕的動作比按鈕重要得多。我經常匿名創建按鈕,不關心給他們賦予變量名稱或引用它們,而是引用傳入按鈕的Action(AbstractAction派生對象)。 –