0

I am having an issues using java awt, specially related to unintended repetition. My aim is to increase the stock my the amount entered each time with an accumulator, however this does not work as intended after the first time adding stock. The details are as follows:

The code which is causing the problem begins in the portfolio class, but I have posted all of my code anyway.

In the portfolio and Action2 innerclass (called from the buy() method), where it says st1.increaseAmount(quantity), it increases the quantity of a certain product. The first time I click buy it works fine. But the second time occurs twice, then the third time, three times etc.

I have tested this my printing "test" in the Action2 class and similarly the first time I want to buy more stock it is printed once, the second time it prints twice, the third time three times, etc.

so e.g. this is what is printed if I go through buying stock 3 times:

test

test
test

test
test
test

whereas I want it to just print:

test

test

test

which would properly add the correct amount of stock.

Any help is very much appreciated.

Thanks!

import java.awt.*;
import java.awt.event.*;

public class run
{
    public static void main (String[] args)
    {
        new simulation();
    }

}


public class simulation implements ActionListener
{
    private Frame f;
    private TextField t = new TextField(10);


    public simulation()
    {
        f = new Frame("portfolio");
        f.setSize(400,200);
        f.setLayout(new FlowLayout());
        Label l = new Label("Enter your name");

        Button b = new Button("Continue");
        b.addActionListener(this);
        f.add(l); f.add(t); f.add(b);
        f.setVisible(true);


        f.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            };
        });

    }

    public void actionPerformed(ActionEvent e)
    {
        String name = t.getText();
        portfolio p = new portfolio(name);
        f.removeNotify();

    }
}


public class portfolio implements ActionListener
{


    private stock st1 = new Volksdragon();

    private String name;
    private Frame f;
    private Button buyShares = new Button("Buy shares");
    private Button sellShares = new Button("Sell shares");

    private Frame f1 = new Frame("Buy stocks");
    private List s = new List(1, false);
    private List s1 = new List(1, false);
    private Button b = new Button("Buy");
    private String share = "";
    private TextField tf = new TextField("Amount");

    public portfolio(String name)
    {
        this.name = name;
        tradeDisplay();
    }

    public void tradeDisplay()
    {
        f = new Frame(name + "'s portfolio");
        f.setSize(400,200);
        f.setLayout(new FlowLayout());

        buyShares.addActionListener(this);
        sellShares.addActionListener(this);

       f.add(buyShares); f.add(sellShares);

        f.setVisible(true);
        f.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            };
        }); 
    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getActionCommand().equals("Buy shares"))
        {
            buy();
        }
        else if (e.getActionCommand().equals("Sell shares"))
        {

        }
    }

    public void buy()
    {
        f1.setSize(400,200);
        f1.setLayout(new FlowLayout());

        Label p1 = new Label("Volksdragon price: \u00A3" + st1.getPrice());


        s.add("Cars");

        s.addActionListener(new Action1());
        s1.addActionListener(new Action3());
        b.addActionListener(new Action2(p1));


        f1.add(s); f1.add(s1); f1.add(b); f1.add(tf);
        f1.add(p1);
        f1.setVisible(true);

        f1.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                System.exit(0);
            };
        });
    }


    class Action1 implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            String choice = e.getActionCommand();

            if (choice.equals("Cars"))
            {
                s1.removeAll();
                s1.add("Volksdragon");
            }
        }
    }

     class Action2 implements ActionListener
     {
        Label l1;

        public Action2(Label p1)
        {
           l1 = p1;
        }

        public void actionPerformed(ActionEvent e1)
        {
            f1.remove(l1);
            String choice1 = e1.getActionCommand();
            double quantity = Double.parseDouble(tf.getText());

            if (choice1.equals("Buy"))
            {                                    
                st1.increaseAmount(quantity);
            }

            f1.dispose();

            System.out.println("test");
        }
    }

    class Action3 implements ActionListener
    {
        public void actionPerformed(ActionEvent e2)
        {
            share = e2.getActionCommand();
        }
    }  

}

public class stock
{
    private double price;
    private double amount;
    private double market;
    private boolean boom;
    private final String name;

    public stock(double amount, String name)
    {
        this.amount = amount;
        this.name = name;
        boom = (Math.random() < 0.5 ? true : false);
        setMarket(0.6);
    }

    public void setMarket(double stockValue)
    {
        market = stockValue*Math.random();

        if(boom == true)
        {
            price = market*100;
        }
        else
        {
            price = market*40;
        }
    }

    public double getPrice()
    {
        return price;
    }

    public String getName()
    {
        return name;
    }

    public double getAmount()
    {
        return amount;
    }

    public void increaseAmount(double value)
    {
        amount += value;
    }

    public void decreaseAmount(double value)
    {
        amount -= value;
    }
}

    public class carStock extends stock
    {
        private double carMarket = Math.random();

        public carStock(double amount, String name)
        {
        super(amount, name);
        }
    }

    public class Volksdragon extends carStock
    {
        public Volksdragon()
        {
            super(0, "Volksdragon");
        }
    }
Rpp
  • 103
  • 1
  • 12
  • Why use AWT? See [this answer](http://stackoverflow.com/questions/6255106/java-gui-listeners-without-awt/6255978#6255978) for many good reasons to abandon AWT components in favor of Swing. – Andrew Thompson Feb 28 '17 at 01:41

1 Answers1

2

You're re-adding ActionListeners (as I mentioned in your previous similar deleted question). Here, every time the simulation listener is called, a new portfolio is created, which calls tradeDisplay which creates a new Frame, but using the same old buyShares button and re-adding an ActionListener to the buyShares button in the process.

Solution: don't re-create Frames and components but instead re-use. Myself, I'd swap components with a CardLayout. The tutorial can be found here: CardLayout tutorial.

More importantly, learn to mentally walk through your code to see what is happening as its running. This is an invaluable and in fact necessary skill if you're going to program.

Also you will want to learn to reduce your code to the minimal, enough to compile, run and show the problems, and nothing else... and follow Java naming conventions so that your code is easy to understand. For example, if I reduced your code and corrected capitalization like so:

import java.awt.*;
import java.awt.event.*;

public class Run {
    public static void main(String[] args) {
        new Portfolio("John Smith");
    }
}

class Portfolio implements ActionListener {
    private String name;
    private Frame f;
    private Button buyShares = new Button("Buy shares");
    private Frame f1 = new Frame("Buy stocks");
    private Button b = new Button("Buy");

    public Portfolio(String name) {
        this.name = name;
        tradeDisplay();
    }

    public void tradeDisplay() {
        f = new Frame(name + "'s portfolio");
        f.setSize(400, 200);
        f.setLayout(new FlowLayout());
        buyShares.addActionListener(this);
        f.add(buyShares);
        f.setVisible(true);
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            };
        });
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("Buy shares")) {
            buy();
        }
    }

    public void buy() {
        f1.setSize(400, 200);
        f1.setLayout(new FlowLayout());
        b.addActionListener(new Action2());
        f1.add(b);
        f1.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            };
        });
        f1.setVisible(true);
    }

    class Action2 implements ActionListener {

        public void actionPerformed(ActionEvent e1) {
            f1.dispose();
            System.out.println("test");
        }
    }
}

You'll see that swapping the f1 JFrame creation to the Portfolio constructor solved your problem. Now the ActionListener is added only once:

import java.awt.*;
import java.awt.event.*;

public class Run {
    public static void main(String[] args) {
        new Portfolio("John Smith");
    }
}

class Portfolio implements ActionListener {
    private String name;
    private Frame f;
    private Button buyShares = new Button("Buy shares");
    private Frame f1 = new Frame("Buy stocks");
    private Button b = new Button("Buy");

    public Portfolio(String name) {
        f1.setSize(400, 200);
        f1.setLayout(new FlowLayout());
        b.addActionListener(new Action2());
        f1.add(b);
        f1.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            };
        });

        this.name = name;
        tradeDisplay();
    }

    public void tradeDisplay() {
        f = new Frame(name + "'s portfolio");
        f.setSize(400, 200);
        f.setLayout(new FlowLayout());
        buyShares.addActionListener(this);
        f.add(buyShares);
        f.setVisible(true);
        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            };
        });
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getActionCommand().equals("Buy shares")) {
            buy();
        }
    }

    public void buy() {
        // f1.setSize(400, 200);
        // f1.setLayout(new FlowLayout());
        // b.addActionListener(new Action2());
        // f1.add(b);
        // f1.addWindowListener(new WindowAdapter() {
        // public void windowClosing(WindowEvent e) {
        // System.exit(0);
        // };
        // });
        f1.setVisible(true);
    }

    class Action2 implements ActionListener {

        public void actionPerformed(ActionEvent e1) {
            f1.dispose();
            System.out.println("test");
        }
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373