1

I made jbutton and added ActionListner to it but the code in public void actionPerformed(ActionEvent e){} exectues twice.It prints test twice,instead of just once.Here is my code

JButton testbut=new JButton("Test");
 ListenForButton2 l=new ListenForButton2();
 testbut.addActionListener(l);
private class ListenForButton2 implements ActionListener{
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == testbut){System.out.println("tEST");}       
    }
}

Here is complete code,in case this is no eneough.Looks like problem was adding two action listeners to my button."if (testbut.getActionListeners().length<1)) testbut.addActionListener(l); "fixed it.But can you find where i added two action listeneres to test button

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Arc2D;
import java.awt.geom.CubicCurve2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.QuadCurve2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Game extends JFrame {

    JButton but1 = new JButton("MakeMoney");
    JButton button1 = new JButton("Current money"); 
    JButton testbut=new JButton("Make money");
    int money = 0;
    double currentMoney;
    String moneyString = "";
    String box1txt="Text for box one";  
    String[] boxtext={"Newspaper Delivery","Car wash","Pizza Delivery","Donut shop","Shrimp boat","Hockey team","Movie Studio","Bank","Oil Company"};
    String[] prices={"60.00","720.00","8,640.00","103,680.00","1,244,160.00","14,929,920.00","179,159,040.00","2.149 billion","25.798 billion"};
    public static void main(String[] args) {
        new Game();
    }

    public Game() {

        try {
            this.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:/Users/TPC/workspace/ProjectMoney/Resources/backgroundForApp.png")))));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        this.setLayout(new BorderLayout());

        button1.setContentAreaFilled(false);

        ListenForButton lforButton = new ListenForButton();
        but1.addActionListener(lforButton);

        JPanel thePanel = new JPanel();
        thePanel.add(button1);
        thePanel.add(but1);
        //thePanel.add(testbut);


        this.setSize(1042, 617);
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setTitle("Project Money");
        this.add(thePanel, BorderLayout.NORTH);
        this.add(new DrawStuff(), BorderLayout.CENTER);
        this.setResizable(true);
        this.setVisible(true);

        Sound sound1 = new Sound();
        String sound = "file:C:/Users/TPC/Downloads/sound.wav";
        sound1.playMusic(sound);

    }

    private class ListenForButton implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            if (e.getSource() == but1) {
                money += 10;
                moneyString = Integer.toString(money);
                button1.setText("$" + moneyString);

            }

        }
    }
private class ListenForButton2 implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == testbut){System.out.println("tEST");}

    }



}

    private class DrawStuff extends JComponent {

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D graph2 = (Graphics2D) g;
            graph2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);










            Shape drawRoundRec = new RoundRectangle2D.Double(170,40,250,66,45, 45);

           //first num xpos,secound num ypost,third num sirina,fourht num duzina
int x1=170; int y1=40; int x2=250; int y2=66; int def=45;
            Shape drawRoundRec2=new RoundRectangle2D.Double(x1,(y1+80),x2,y2,def,def);
            Shape drawRoundRec3=new RoundRectangle2D.Double(x1,(y1+80+80),x2,y2,def,def);
            Shape drawRoundRec4=new RoundRectangle2D.Double(x1,(y1+80+80+80),x2,y2,def,def);
            Shape drawRoundRec5=new RoundRectangle2D.Double(x1,(y1+80+80+80+80),x2,y2,def,def);
            Shape drawRoundRect6=new RoundRectangle2D.Double(x1+330,40,250,66,def, def);
            Shape drawRoundRect7=new RoundRectangle2D.Double(x1+330,(y1+80),250,66,def, def);
            Shape drawRoundRect8=new RoundRectangle2D.Double(x1+330,(y1+80+80),250,66,def, def);   
            Shape drawRoundRect9=new RoundRectangle2D.Double(x1+330,(y1+80+80+80),250,66,def, def);
            Shape drawRoundRect10=new RoundRectangle2D.Double(x1+330,(y1+80+80+80+80),250,66,def, def);

            graph2.setPaint(Color.BLACK);



            graph2.setColor(Color.LIGHT_GRAY);

            graph2.fill(drawRoundRec); graph2.fill(drawRoundRec2);
            graph2.fill(drawRoundRec3); graph2.fill(drawRoundRec4); graph2.fill(drawRoundRec5); graph2.fill(drawRoundRect6);
            graph2.fill(drawRoundRect7); graph2.fill(drawRoundRect8); graph2.fill(drawRoundRect9); graph2.fill(drawRoundRect10);
            graph2.setPaint(Color.BLACK);

             graph2.draw(drawRoundRec2); graph2.draw(drawRoundRec3); graph2.draw(drawRoundRec4);
            graph2.draw(drawRoundRec5);  graph2.draw(drawRoundRect6); graph2.draw(drawRoundRect7);  graph2.draw(drawRoundRect8); 
            graph2.draw(drawRoundRect9); graph2.draw(drawRoundRect10);
            Font font=new Font("Serif",Font.PLAIN,30);
            g.setFont(font); g.drawString(box1txt,190,80); g.drawString(boxtext[0],190,150); g.drawString(boxtext[1],190,150+80); g.drawString(boxtext[2],190,150+90+70);
            g.drawString(boxtext[3],190,150+90+70+80);

            g.drawString(boxtext[4],520,80); g.drawString(boxtext[5],520,150); g.drawString(boxtext[6],520,150+80); g.drawString(boxtext[7],520,150+90+70);
            g.drawString(boxtext[8],520,150+90+70+80);



             g.drawString(prices[0],190,150+30); g.drawString(prices[1],190,150+80+30); g.drawString(prices[2],190,150+90+70+30);
            g.drawString(prices[3],190,150+90+70+80+30);

            g.drawString(prices[4],520,80+25); g.drawString(prices[5],520,150+30); g.drawString(prices[6],520,150+80+30); g.drawString(prices[7],520,150+90+70+30);
            g.drawString(prices[8],520,150+90+70+80+30);
            testbut.setLocation(180,70);
            Dimension d = new Dimension(100,40);
            testbut.setSize(d);
           ListenForButton2 l=new ListenForButton2();
           if (testbut.getActionListeners().length<1) testbut.addActionListener(l);







            this.add(testbut);
        }
    }
}
  • 6
    For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). – Andrew Thompson Aug 25 '15 at 13:37
  • 5
    There is not enough here to reproduce your problem. ActionListeners do not in general fire twice for each action. – khelwood Aug 25 '15 at 13:38
  • I'd suggest doing a debug run (with breakpoint on the actionPerformed method), so that you can see the callers and the ActionEvent instances. – tjalling Aug 25 '15 at 13:40
  • Please post that part of the code that has the ailment. Here it's not pointing to the problem. – Hanzallah Afgan Aug 25 '15 at 13:40
  • 1
    thanks for info,next time i will read and use SSCE and MCV exemple.Now i posted whole code.Can i find where problem was."if (testbut.getActionListeners().length<1)) testbut.addActionListener(l); "Fixed it but i still dont know where i added two action listeners to test button – Nemanja Milosevic Aug 25 '15 at 14:41

1 Answers1

4

Make sure to add your action listener just once.

You get the listeners count via testbut.getActionListeners().length .


Update - multiple calls

Within the paintComponent of the DrawStuff class which extends JComponent you are only adding the listener once. Same as for the first listener.

The difference is, the first is added within a constructor. While the paintComponent method of the JComponent which can be called multiples times.

As to how and when it is called, this answer might help you.

Community
  • 1
  • 1
Laurentiu L.
  • 6,566
  • 1
  • 34
  • 60
  • 1
    I don't see it being added a second time in the original code – Stultuske Aug 25 '15 at 13:45
  • 1
    But you also don't see where the code is being called from. – Laurentiu L. Aug 25 '15 at 13:45
  • 1
    @AndrewThompson As a rule of thumbs, sure. But do you think in this case it would be possible for anything else to be the case other than him adding the listener multiple times? I'm not justifying him not adding the complete details, but my preemptive answer based on intiuitive reasoning. – Laurentiu L. Aug 25 '15 at 13:48
  • 1
    That is your choice and rightfully so, same as i consider mine applicable. Should it be a blunder, it would mean no more than editing an answer or deleting it at worst. – Laurentiu L. Aug 25 '15 at 13:52
  • Thanks that helped,sorry for not posting full info,now i edited it.Can you find where i added two action listeners to test button? @AndrewThompson – Nemanja Milosevic Aug 25 '15 at 14:44
  • Thanks that helped,sorry for not posting full info,now i edited it.Can you find where i added two action listeners to test button? @LaurentiuL. – Nemanja Milosevic Aug 25 '15 at 14:45
  • @user2683843 I have updated the answer based on your code to point out how the multiple calls can occur. – Laurentiu L. Aug 25 '15 at 14:49
  • @AndrewThompson left just the part for tracking listeners count. Cheers – Laurentiu L. Aug 25 '15 at 15:18
  • *"left just the part for tracking listeners count"* Yep, that's a good debugging tip. :) – Andrew Thompson Aug 25 '15 at 15:26