Action Listener检测单个事件的多个事件

时间:2014-01-15 23:47:12

标签: java eclipse swing actionlistener

我设计了一个面板,其中包含一些按钮。按钮附加一个ActionListener。当我单击该按钮时,此ActionListener会为此单击检测到4个事件。而它应该只检测一个。有人知道究竟是什么原因吗?

public class Buttons extends JPanel
{
private JButton undo=new JButton("Undo");
private JButton replay=new JButton("Replay");

public void paint(Graphics g)
{
    super.paint(g);
    super.setSize(new Dimension(560,30));
    super.add(replay);
    super.add(undo);
    undo.setBorder(new LineBorder(Color.WHITE,3));
    replay.setBorder(new LineBorder(Color.WHITE,3));

    undo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
            Controler.pieces.undo();
            Controler.reDraw();

        }
    });
    replay.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
            System.out.println("Dastiii");
        }
    });

}
 }

这些事件正在这里使用

public void undo()
{
    System.out.print(Controler.allMoves.size());
    if(Controler.allMoves.size()<=1)
    {
        init_board();
        return;
    }
    Piece temp[][]=Controler.allMoves.get(Controler.allMoves.size()-2);
    for(int i=0;i<8;i++)
    {
        for(int j=0;j<8;j++)
        {
            board[i][j].set_name(temp[i][j].get_name());
            board[i][j].set_oneWay(temp[i][j].get_oneWay());
        }
    }
    Controler.allMoves.remove(Controler.allMoves.size()-2);
}

1 个答案:

答案 0 :(得分:3)

您在ActionListener方法中注册了paint !!

我们甚至不担心不建议覆盖paint

永远不要在任何paint方法中更改或修改组件或其任何子组件的状态,这些组件将在应用程序执行期间多次调用。例如,当主窗口可见时,paint方法被调用2-4次并不罕见......

public void paint(Graphics g)
{
    super.paint(g);
    /** All this should be done within the constructor
    // If you are using a layout manager, this is pointless, if your not
    // then that's another problem
    super.setSize(new Dimension(560,30));
    super.add(replay);
    super.add(undo);
    undo.setBorder(new LineBorder(Color.WHITE,3));
    replay.setBorder(new LineBorder(Color.WHITE,3));

    undo.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
            Controler.pieces.undo();
            Controler.reDraw();

        }
    });
    replay.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
            System.out.println("Dastiii");
        }
    });
    **/

}

看看:

有关Swing

中的绘画方式和内容的更多详细信息