将ActionListeners添加到直接添加到容器中的按钮

时间:2012-10-20 06:55:00

标签: java awt actionlistener grid-layout

我试图创建一个自定义JPanel,我在我的GUI设置中添加到卡片布局中。在这个自定义布局中,我使用gridlayout并将按钮直接添加到容器中。我现在需要为这些按钮添加actionlisteners,不知道如何。任何帮助将不胜感激,请在下面找到自定义课程。

import java.awt.*; import java.awt.event.*; import javax.swing.*;

public class PuzzleSudokuPanel extends JPanel{
  int[][] grid =     
{{0, 0, 0, 5, 0, 0, 8, 3, 1},
 {0, 5, 3, 0, 0, 8, 7, 0, 0},      
 {7, 0, 0, 0, 4, 2, 0, 6, 0},
 {0, 0, 9, 0, 3, 0, 0, 7, 8},
 {0, 0, 2, 4, 0, 6, 1, 0, 0},
 {6, 3, 0, 0, 9, 0, 2, 0, 0},
 {0, 1, 0, 7, 6, 0, 0, 0, 9},
 {0, 0, 4, 9, 0, 0, 5, 8, 0},
 {2, 9, 7, 0, 0, 3, 0, 0, 0}};
Container myGrid = new Container();

public PuzzleSudokuPanel ()throws NullPointerException{
  try{
    for(int i = 0; i<9; i++){
      for(int j = 0; j<9; j++){
        String appropriateNumber = convertSimple(grid[i][j]);
        myGrid.add(new JButton(appropriateNumber));
      }
    }
  }
  catch(NullPointerException e){

  }
  myGrid.setLayout(new GridLayout(9, 9));
  myGrid.setPreferredSize (new Dimension(400, 400)); 

  add(myGrid);
  }
    public static String convertSimple(int a){
    return ("" + a);
  }
}

[编辑]

calkuro代码:

import java.awt.*; import java.awt.event.*; import javax.swing.*;

 public class PuzzleCalkuroPanel extends JPanel{
  String[][] grid =     
  {{"3/", "3/", "3-", "8x"},
    {"9+", "9+", "3-", "8x"},      
    {"9+", "9+2", "9+2", "8x"},
    {"1", "9+2", "1-", "1-"}};
  Container myGrid = new Container();

  public PuzzleCalkuroPanel ()throws NullPointerException{
    try{
      for(int i = 0; i<4; i++){
        for(int j = 0; j<4; j++){
          JButton button = new JButton(grid[i][j]);
          button.addActionListener(new calkuroListener());
          myGrid.add(new JButton(grid[i][j]));
        }
      }
    }
    catch(NullPointerException e){

    }
    myGrid.setLayout(new GridLayout(4, 4));
    myGrid.setPreferredSize (new Dimension(400, 400)); 

    add(myGrid);
  }
  private class calkuroListener implements ActionListener{
    public void actionPerformed (ActionEvent event){
      String numStr = JOptionPane.showInputDialog("Enter a number to change to: ");
      JOptionPane.showMessageDialog(null, numStr);
    }
  }
}

1 个答案:

答案 0 :(得分:2)

而不是......

myGrid.add(new JButton(appropriateNumber));

做...

JButton button = new JButton(appropriateNumber);
button.addActionListener(...);
myGrid.add(button);

<强>已更新

这就是你正在做的......

JButton button = new JButton(grid[i][j]); // Create button here, good...
button.addActionListener(new calkuroListener()); // Add listener here, good...
myGrid.add(new JButton(grid[i][j])); // Create a new button here, bad...

这就是你应该做的事情

JButton button = new JButton(grid[i][j]); // Create button here, good...
button.addActionListener(new calkuroListener()); // Add listener here, good...
myGrid.add(button); // Add button here, good...