1

我试图创建一个自定义 JPanel,我将其添加到我的 GUI 设置中的卡片布局中。在这个自定义布局中,我使用网格布局并将按钮直接添加到容器中。我现在需要向这些按钮添加动作侦听器,但不知道如何。任何帮助将不胜感激,请在下面找到自定义类。

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);
  }
}

[编辑]

卡尔库罗代码:

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);
    }
  }
}
4

1 回答 1

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...
于 2012-10-20T07:00:14.147 回答