行动只执行一次

时间:2014-03-22 19:39:34

标签: java swing

我有一张gridLayout的表单,其中包含15个JButtons和一个JLabel。每个按钮都有一个动作,当它被触发时它应该显示clicked!,执行一些操作并在控制台中显示它的位置。

但它只在控制台中显示一次位置 - 当我第一次按下任何按钮时。之后,控制台中仅显示clicked文本。

问题是什么?

public class PuzzleUI extends JFrame {

private static final long serialVersionUID = 1L;
private int gap = 2;

private Puzzle puzzle;
private JComponent[][] itemGrid;
private JPanel controls;

public PuzzleUI(String title, int puzzles, int empty_cell) {
    super(title);
    puzzle = new Puzzle(puzzles, empty_cell);
    itemGrid = new JComponent[puzzle.getRowSize()][puzzle.getRowSize()];
    controls = new JPanel();
    controls.setLayout(new GridLayout(puzzle.getRowSize(), puzzle
            .getRowSize(), gap, gap));
    init(this.getContentPane());
}

public void init(final Container pane) {

    ActionListener al = new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            Object ob = e.getSource();
            boolean finished = false;
            if (ob instanceof JButton) {
                System.out.println("Clicked!");
                int cnt = 0;
                label: for (int i = 0; i < itemGrid.length; i++)
                    for (int j = 0; j < itemGrid[i].length; j++) {
                        if (itemGrid[i][j] == (JButton) ob) {
                            System.out.println(i + "-" + j); // appeared only once
                            finished = puzzle.swap(cnt);
                            break label;
                        }
                        cnt++;
                    }
                PuzzleUI.this.init(PuzzleUI.this.getContentPane());
                PuzzleUI.this.controls.repaint();
                if (finished == true)
                    JOptionPane.showMessageDialog(
                            PuzzleUI.this,
                            "FINISHED WITH MOVE: "
                                    + PuzzleUI.this.puzzle.getMoves());
            }
        }
    };

    int cnt = 0;
    for (int i = 0; i < itemGrid.length; i++)
        for (int j = 0; j < itemGrid[i].length; j++) {
            int value = puzzle.getListItem(cnt);
            if (value == puzzle.getEmptyFlag())
                itemGrid[i][j] = new JLabel("");
            else {
                JButton jb = new JButton(String.valueOf(value));
                jb.addActionListener(al);
                itemGrid[i][j] = jb;
            }
            controls.add(itemGrid[i][j]);
            cnt++;
        }
    pane.add(controls);
}
}

0 个答案:

没有答案