How to find a button source in AWT (calculator homework)

前端 未结 2 1989
夕颜
夕颜 2020-11-21 22:15

We were asked to make a simple GUI calculator, I used getSource() to detect the buttons, cause that\'s what they taught us. It works by typing the 1st and 2nd value then cho

相关标签:
2条回答
  • 2020-11-21 22:37

    You can check if your source is a Button (not actually nessesary since you should know it is only called from a button) and then type cast to a button and use .getText()

    String sourceText;
    if (ae.getSource() instanceof Button) {
    sourceText = ((Button)ae.getSource()).getText();
    }
    
    0 讨论(0)
  • 2020-11-21 22:52

    I would tend to have each button for the numbers, as well as each button for operands, add text to a text field that is the 'Input/Output'.

    Also have a button = (equals). When the = button is activated, call the ScriptEngine to evaluate the content of the I/O text field and write the result back to it.

    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 final JTextField io = new JTextField(15);
        private final ArrayList<JButton> controls = new ArrayList<>();
        private final JPanel ui = new JPanel(new BorderLayout(2, 2));
        private ScriptEngine engine;
    
        ScriptEngineCalculator() {
            initUI();
        }
    
        public final void initUI() {
            // obtain a reference to the JS engine
            engine = new ScriptEngineManager().getEngineByExtension("js");
    
            JPanel text = new JPanel(new GridLayout(0, 1, 3, 3));
            ui.add(text, BorderLayout.PAGE_START);
            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();
            switch (command) {
                case "C":
                    io.setText("");
                    break;
                case "=":
                    calculateResult();
                    break;
                default:
                    io.setText(io.getText() + command);
                    break;
            }
        }
    
        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(() -> {
                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);
            });
        }
    }
    
    0 讨论(0)
提交回复
热议问题