如何在AWT中找到按钮源(计算器作业)

时间:2011-09-16 07:46:48

标签: java awt

我们被要求制作一个简单的GUI计算器,我使用getSource()来检测按钮,这就是他们教给我们的东西。它通过键入第一个和第二个值然后选择操作来工作,它工作。但我犯了一个错误,因为他们要我们做的是数字也应该是按钮,就像真正的计算器一样。那么如何使用getSource()获取每个按钮的值?就像当我按下按钮1和2等于3.继承人我做了什么

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

public class SimpleCalculator implements ActionListener
{
    // containers
    private Frame f;
    private Panel p1, p2, p3, p4;

    // components
    private Label l1, l2, l3;
    private TextField tf1, tf2, tf3;
    private Button bAdd, bSub, bMul, bDiv, bClear;

    public SimpleCalculator()
    {
        f = new Frame("My First GUI App");

        p1 = new Panel();
        p2 = new Panel();
        p3 = new Panel();
        p4 = new Panel();

        l1 = new Label("First: ");
        l2 = new Label("Second: ");
        l3 = new Label("Result: ");

        tf1 = new TextField(15);
        tf2 = new TextField(15);
        tf3 = new TextField(15);

        bAdd = new Button("+");
        bSub = new Button("-");
        bMul = new Button("*");
        bDiv = new Button("/");
        bClear = new Button("C");
    }
    public void launchFrame()
    {
        // use default layout manager of the Panel (FlowLayout)
        p1.add(l1);
        p1.add(tf1);

        p2.add(l2);
        p2.add(tf2);

        p3.add(l3);
        p3.add(tf3);

        p4.add(bAdd);
        p4.add(bSub);
        p4.add(bMul);
        p4.add(bDiv);
        p4.add(bClear);

        // change the layout manager of the Frame, 
        // use GridLayout(4, 1)
        f.setLayout(new GridLayout(4, 1));

        f.add(p1);
        f.add(p2);
        f.add(p3);
        f.add(p4);

        f.pack();
        f.setVisible(true);

        // register event handlers
        bAdd.addActionListener(this);
        bSub.addActionListener(this);
        bMul.addActionListener(this);
        bDiv.addActionListener(this);
        bClear.addActionListener(this);

        f.addWindowListener(new MyCloseButtonHandler());
    }
    // override the actionPerformed method
    public void actionPerformed(ActionEvent ae)
    {
        Object source = ae.getSource();
        double num1, num2, result = 0.0;

        if (tf1.getText() != null && tf2.getText() != null)
        {
            num1 = Double.parseDouble(tf1.getText());
            num2 = Double.parseDouble(tf2.getText());

            if (source == bAdd)
                result = num1 + num2;
            else if (source == bSub)
                result = num1 - num2;
            else if (source == bMul)
                result = num1 * num2;
            else if (source == bDiv)
                result = num1 / num2;
            else if (source == bClear)
            {
                tf1.setText("0.0");
                tf2.setText("0.0");
                tf3.setText("0.0");
            }
            else {}
            // tf3.setText(new Double(result).toString());
            tf3.setText("" + result);
        }
    }
    private class MyCloseButtonHandler extends WindowAdapter
    {
        public void windowClosing(WindowEvent we)
        {
            System.exit(0);
        }
    }
    public static void main(String args[])
    {
        SimpleCalculator sc = new SimpleCalculator();
        sc.launchFrame();
    }
}

2 个答案:

答案 0 :(得分:16)

我倾向于拥有数字的每个按钮,以及操作数的每个按钮,将文本添加到“输入/输出”的文本字段。

还有一个按钮=。激活=按钮后,调用javax.script.ScriptEngine评估I / O文本字段的内容并将结果写回给它。

E.G。

Calculet input = Calculet output

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.util.ArrayList;

// script package introduced in Java 1.6
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

class ScriptEngineCalculator implements ActionListener, KeyListener {

    private JTextField io;
    private ScriptEngine engine;
    private ArrayList<JButton> controls;
    private JPanel ui;

    ScriptEngineCalculator() {
        initUI();
    }

    public final void initUI() {
        // obtain a reference to the JS engine
        engine = new ScriptEngineManager().
                getEngineByExtension("js");

        ui = new JPanel(new BorderLayout(2, 2));
        controls = new ArrayList<JButton>();

        JPanel text = new JPanel(new GridLayout(0, 1, 3, 3));
        ui.add(text, BorderLayout.PAGE_START);
        io = new JTextField(15);
        Font font = io.getFont();
        font = font.deriveFont(font.getSize() * 1.8f);
        io.setFont(font);
        io.setHorizontalAlignment(SwingConstants.TRAILING);
        io.setFocusable(false);
        text.add(io);

        JPanel buttons = new JPanel(new GridLayout(4, 4, 2, 2));
        ui.add(buttons, BorderLayout.CENTER);
        String[] keyValues = {
            "7", "8", "9", "/",
            "4", "5", "6", "*",
            "1", "2", "3", "-",
            "0", ".", "C", "+"
        };

        for (String keyValue : keyValues) {
            addButton(buttons, keyValue);
        }

        JButton equals = new JButton("=");
        configureButton(equals);
        ui.add(equals, BorderLayout.LINE_END);

        ui.setBorder(new EmptyBorder(5, 5, 5, 5));
    }

    public JComponent getUI() {
        return ui;
    }

    public void addButton(Container c, String text) {
        JButton b = new JButton(text);
        configureButton(b);
        c.add(b);
    }

    public void configureButton(JButton b) {
        Font f = b.getFont();
        b.setFont(f.deriveFont(f.getSize() * 1.5f));
        b.addActionListener(this);
        b.addKeyListener(this);
        controls.add(b);
    }

    public void calculateResult() {
        try {
            Object result = engine.eval(io.getText());
            if (result == null) {
                io.setText("Output was 'null'");
            } else {
                io.setText(result.toString());
            }
        } catch (ScriptException se) {
            io.setText(se.getMessage());
        }
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        String command = ae.getActionCommand();
        if (command.equals("C")) {
            io.setText("");
        } else if (command.equals("=")) {
            calculateResult();
        } else {
            io.setText(io.getText() + command);
        }
    }

    private JButton getButton(String text) {
        for (JButton button : controls) {
            String s = button.getText();
            if (text.endsWith(s)
                    || (s.equals("=")
                    && (text.equals("Equals") || text.equals("Enter")))) {

                return button;
            }
        }
        return null;
    }

    /* START - Because I hate mice. */
    @Override
    public void keyPressed(KeyEvent ke) {
    }

    @Override
    public void keyReleased(KeyEvent ke) {
        String s = KeyEvent.getKeyText(ke.getKeyCode());
        JButton b = getButton(s);
        if (b != null) {
            b.requestFocusInWindow();
            b.doClick();
        }
    }

    @Override
    public void keyTyped(KeyEvent ke) {
    }
    /* END - Because I hate mice. */

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                ScriptEngineCalculator sc = new ScriptEngineCalculator();
                JFrame f = new JFrame("Calculet");
                f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                f.setContentPane(sc.getUI());
                f.pack();
                f.setMinimumSize(f.getSize());
                f.setLocationByPlatform(true);
                f.setVisible(true);
            }
        });
    }
}

答案 1 :(得分:3)

你可以检查你的源是否是一个Button(实际上并不是nessesary,因为你应该知道它只是从一个按钮调用),然后输入一个按钮并使用.getText()

String sourceText;
if (ae.getSource() instanceof Button) {
sourceText = ((Button)ae.getSource()).getText();
}