【问题标题】:Java awt unintended repetition issueJava awt意外重复问题
【发布时间】:2017-07-17 08:24:35
【问题描述】:

我在使用 java awt 时遇到问题,特别是与意外重复有关。 我的目标是通过累加器每次输入的金额增加库存,但是在第一次添加库存后,这并没有按预期工作。详情如下:

导致问题的代码从投资组合类开始,但我已经发布了我的所有代码。

在投资组合和 Action2 内部类(从 buy() 方法调用)中,它说 st1.increaseAmount(quantity),它增加了某个产品的数量。我第一次点击购买它工作正常。但是第二次出现两次,然后是第三次,三次等等。

我已经在 Action2 类中测试了我的打印“测试”,类似地,我第一次想购买更多库存时打印一次,第二次打印两次,第三次打印三次,等等。

例如这是我购买股票 3 次后打印的内容:

测试

测试
测试

测试
测试
测试

而我希望它只打印:

测试

测试

测试

这将正确添加正确数量的库存。

非常感谢任何帮助。

谢谢!

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

【问题讨论】:

  • 为什么要使用 AWT?请参阅this answer,了解放弃 AWT 组件以支持 Swing 的许多充分理由。

标签: java user-interface events awt


【解决方案1】:

您正在重新添加 ActionListeners(正如我在您之前类似的已删除问题中提到的那样)。在这里,每次调用模拟监听器时,都会创建一个新的投资组合,它会调用 tradeDisplay,它会创建一个新框架,但使用相同的旧 buyShares 按钮并重新添加一个 ActionListener 到 buyShares 按钮过程。

解决方案:不要重新创建框架和组件,而是重复使用。我自己,我会用 CardLayout 交换组件。教程可以在这里找到:CardLayout tutorial

更重要的是,学会在头脑中遍历您的代码,看看它在运行时发生了什么。如果您要编程,这是一项非常宝贵且实际上必不可少的技能。

您还需要学习将代码减少到最少,足以编译、运行和显示问题,仅此而已……并遵循 Java 命名约定,以便您的代码易于理解。例如,如果我像这样减少您的代码并更正大写:

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

您会看到将 f1 JFrame 创建交换到 Portfolio 构造函数解决了您的问题。现在 ActionListener 只添加一次:

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

【讨论】:

  • 谢谢!我会看看我能做什么。
  • @Rpp:请不要删除这个问题。如果您需要修改它,请编辑它。对在这里提供帮助的志愿者不太公平。
  • @Rpp:查看编辑以回答。还请检查为您未来的问题创建minimal reproducible example 程序。
猜你喜欢
  • 1970-01-01
  • 2011-01-11
  • 1970-01-01
  • 2021-01-03
  • 1970-01-01
  • 1970-01-01
  • 2013-06-30
  • 1970-01-01
  • 2017-06-14
相关资源
最近更新 更多