Taschenrechnerereignisse



  • Guten Tag,

    ich versuche gerade einen Taschenrechner zu erstellen, die Oberfläche ist fertig nun brauche ich die Ereignisse. Leider weiß ich nicht was alles möglich ist.

    Was ich realisieren möchte ist:

    - Zahlen nach Knopfdruck im TextField anzeigen lassen
    - mit C das TextField wieder leeren
    - mit +/- die eingegebene Zahl negativ werden lassen
    - mit = das Ergebnis im Textfield ausgeben

    eigentlich auch noch mit dem Pfeil die letzte Zahl wieder wegnehmen aber das lass ich erstmal sein.

    Habt ihr Ideen mit welchen Funktionen das gehen würde?

    Vielen Dank im Voraus

    Das ist mein bisheriger Code:

    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.*;
    
    public class CalcPanel 
    {
      static void addComponent( Container cont,
                                GridBagLayout gbl,
                                Component c,
                                int x, int y,
                                int width, int height,
                                double weightx, double weighty )
      {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.gridx = x; gbc.gridy = y;
        gbc.gridwidth = width; gbc.gridheight = height;
        gbc.weightx = weightx; gbc.weighty = weighty;
        gbl.setConstraints( c, gbc );
        cont.add( c );
      }
    
      public static void main( String[] args )
      {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        Container c = f.getContentPane();
    
        GridBagLayout gbl = new GridBagLayout();
        c.setLayout( gbl );
    
        JTextField field;
        field = new JTextField();
    
        JButton[] numbers = new JButton[10];
        for(int i = 0; i < numbers.length; i++){
        numbers[i] = new JButton(Integer.toString(i));
        }
    
        JButton sum, sub, div, mult;
        sum = new JButton("+");
        sub = new JButton("-");
        div = new JButton("×");
        mult = new JButton("÷");
    
        JButton erg;
        erg = new JButton("="); 
    
        ActionListener al =new ActionListener(){
        	public void actionPerformed(ActionEvent e){
    
        	}
        };
    
        //                                      x  y  w  h  wx   wy
    
        addComponent( c, gbl, field, 0, 0, 4, 1, 1.0, 1.0);
        addComponent( c, gbl, new JButton("C"), 0, 1, 2, 1, 0  , 0 );
        addComponent( c, gbl, new JButton("←"), 2, 1, 1, 1, 0  , 0 );
        addComponent( c, gbl, div , 3, 1, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[7], 0, 3, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[4], 0, 4, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[1], 0, 5, 1, 1, 0  , 0 );
        addComponent( c, gbl, new JButton("+/-"), 0, 6, 1, 1, 0, 0 );
        addComponent( c, gbl, numbers[8], 1, 3, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[5], 1, 4, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[2], 1, 5, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[0], 1, 6, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[9], 2, 3, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[6], 2, 4, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[3], 2, 5, 1, 1, 0  , 0 );
        addComponent( c, gbl, new JButton(","), 2, 6, 1, 1, 0  , 0 );
        addComponent( c, gbl, mult, 3, 3, 1, 1, 0  , 0 );
        addComponent( c, gbl, sub, 3, 4, 1, 1, 0  , 0 );
        addComponent( c, gbl, sum, 3, 5, 1, 1, 0  , 0 );
        addComponent( c, gbl, erg, 3, 6, 1, 1, 0 , 0 );
    
        f.setSize( 250, 250);
        f.setVisible( true );
      }
    }
    


  • Du benötigst einen ActionListener für den Button-Click: Using JButton

    Und in der Methode actionPerformed() führst du dann die entsprechende Aktion aus.



  • Guten Tag,

    ich habe folgenden Quelltext:

    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.EventObject;
    
    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    import javax.swing.*;
    
    public class CalcPanel 
    
    {
    
    static void addComponent( Container cont,
                                GridBagLayout gbl,
                                Component c,
                                int x, int y,
                                int width, int height,
                                double weightx, double weighty )
      {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.gridx = x; gbc.gridy = y;
        gbc.gridwidth = width; gbc.gridheight = height;
        gbc.weightx = weightx; gbc.weighty = weighty;
        gbl.setConstraints( c, gbc );
        cont.add( c );
    
      }
    
    public static void main( String[] args )
      {
    
        JFrame f = new JFrame();
        f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        Container c = f.getContentPane();
    
        GridBagLayout gbl = new GridBagLayout();
        c.setLayout( gbl );
    
        JTextField field;
        field = new JTextField();
    
        JButton[] numbers = new JButton[10];
        for(int i = 0; i < numbers.length; i++){
        numbers[i] = new JButton(Integer.toString(i));
        }
    
        JButton sum, sub, div, mult;
        sum = new JButton("+");
        sub = new JButton("-");
        div = new JButton("*");
        mult = new JButton("/");
    
        JButton C;
        C=new JButton("C");
    
        JButton erg;
        erg = new JButton("="); 
        JButton point;
        point =new JButton(".");
    
        ActionListener al =new ActionListener(){
        	public void actionPerformed(ActionEvent e){
        		ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
        		 String text = ((JButton)e.getSource()).getText();
        		 field.setText(field.getText()+text);
    
        		 try {
    		            // Evaluate the expression
    		            Object result = engine.eval(field.getText());
    		            String berechnung = String.valueOf(result);
    		            System.out.println(result);
    		      if (e.getSource()==erg){
    		          field.setText(berechnung);
    		          }
        		 }
    
    		        catch (ScriptException h) {
    		            System.out.println("Fehler");
    		            h.printStackTrace();
    		        }
    
        		 if(e.getSource() == sum){
                     field.setText(field.getText());
    
                 }
                 else if(e.getSource() == sub){
                	 field.setText(field.getText());
                 }
                 else if (e.getSource() == mult){
                	 field.setText(field.getText());
                 }
                 else if (e.getSource() == div){
                	 field.setText(field.getText());
                 }
        	}
        };
        ActionListener al2=new ActionListener(){
        	public void actionPerformed(ActionEvent f){
        		field.setText("");
        	}
        };
        ActionListener al3=new ActionListener(){
        	public void actionPerformed(ActionEvent g){
    
        	}
        };
    
        numbers[0].addActionListener(al);
        numbers[1].addActionListener(al);
        numbers[2].addActionListener(al);
        numbers[3].addActionListener(al);
        numbers[4].addActionListener(al);
        numbers[5].addActionListener(al);
        numbers[6].addActionListener(al);
        numbers[7].addActionListener(al);
        numbers[8].addActionListener(al);
        numbers[9].addActionListener(al);
        point.addActionListener(al);
        C.addActionListener(al2);
        sum.addActionListener(al);
        sub.addActionListener(al);
        mult.addActionListener(al);
        div.addActionListener(al);
        erg.addActionListener(al);
    
        //                                      x  y  w  h  wx   wy
    
        addComponent( c, gbl, field, 0, 0, 4, 1, 1.0, 1.0);
        addComponent( c, gbl, C, 0, 1, 2, 1, 0 , 0 );
        addComponent( c, gbl, new JButton("←"), 2, 1, 1, 1, 0  , 0 );
        addComponent( c, gbl, div , 3, 1, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[7], 0, 3, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[4], 0, 4, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[1], 0, 5, 1, 1, 0  , 0 );
        addComponent( c, gbl, new JButton("+/-"), 0, 6, 1, 1, 0, 0 );
        addComponent( c, gbl, numbers[8], 1, 3, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[5], 1, 4, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[2], 1, 5, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[0], 1, 6, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[9], 2, 3, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[6], 2, 4, 1, 1, 0  , 0 );
        addComponent( c, gbl, numbers[3], 2, 5, 1, 1, 0  , 0 );
        addComponent( c, gbl, point, 2, 6, 1, 1, 0  , 0 );
        addComponent( c, gbl, mult, 3, 3, 1, 1, 0  , 0 );
        addComponent( c, gbl, sub, 3, 4, 1, 1, 0  , 0 );
        addComponent( c, gbl, sum, 3, 5, 1, 1, 0  , 0 );
        addComponent( c, gbl, erg, 3, 6, 1, 1, 0 , 0 );
    
        f.setSize( 250, 250);
        f.setVisible( true );
      }
    }
    

    Ich würde gern im 3. ActionListener auf den String berechnung zugreifen.
    Wie kann ich das machen?

    Vielen Dank im Voraus



  • Ciao Detlef

    Hier ein Beispiel für ein Rechner mit den vier Grundoperatoren. Quetsch einfach das raus was bei dir noch fehlt.

    package swing_eins;
    
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyListener;
    import java.util.EventObject;
    
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    
    /**
     *
     * @author Renato
     */
    public class win_start
                           extends JFrame
                           implements ActionListener {
    
      private static final KeyListener keyListener = null;
      private final JTextField         edt_res;
      private Float                    zahl1, zahl2;
      private String                   operator;
    
      public static void main(final String[] args) {
        // TODO Auto-generated method stub
        final win_start fenster = new win_start();
        fenster.setSize(300, 300);
        fenster.setLocation(200, 200);
        fenster.setName("programm");
        fenster.pack();
        fenster.setVisible(true);
      }
    
      public win_start() {
        super("das programm");
    
        // Resultat anzeigen
        final JPanel pn_text = new JPanel();
        final JLabel lbl_name = new JLabel("Zahl");
        pn_text.add(lbl_name);
        edt_res = new JTextField(20);
        edt_res.setToolTipText("Resultat der Berechnung");
        edt_res.addFocusListener(null);
        edt_res.addKeyListener(keyListener);
        pn_text.add(edt_res);
        pn_text.setBorder(BorderFactory.createEtchedBorder());
        getContentPane().add(pn_text, BorderLayout.NORTH);
    
        // Buttons aufbauen
        final JPanel pn_buttons = new JPanel();
        final JPanel pn_eins = new JPanel();
        final JPanel pn_zwei = new JPanel();
        final JPanel pn_drei = new JPanel();
        final JPanel pn_vier = new JPanel();
        final JButton btn_nul = new JButton("0");
        // btn_nul.setLayout(null);
        // btn_nul.setBounds(1, 500, 60, 20);
        btn_nul.addActionListener(this);
        pn_eins.add(btn_nul);
        final JButton btn_eins = new JButton("1");
        btn_eins.addActionListener(this);
        // btn_eins.setLayout(null);
        // btn_eins.setBounds(1, 550, 60, 20);
        pn_eins.add(btn_eins);
        final JButton btn_zwei = new JButton("2");
        // btn_zwei.setLayout(null);
        btn_zwei.addActionListener(this);
        pn_eins.add(btn_zwei);
        final JButton btn_drei = new JButton("3");
        // btn_drei.setLayout(null);
        btn_drei.addActionListener(this);
        pn_eins.add(btn_drei);
        final JButton btn_vier = new JButton("4");
        // btn_vier.setLayout(null);
        btn_vier.addActionListener(this);
        pn_zwei.add(btn_vier);
        final JButton btn_fuenf = new JButton("5");
        // btn_fuenf.setLayout(null);
        btn_fuenf.addActionListener(this);
        pn_zwei.add(btn_fuenf);
        final JButton btn_sechs = new JButton("6");
        // btn_sechs.setLayout(null);
        btn_sechs.addActionListener(this);
        pn_zwei.add(btn_sechs);
        final JButton btn_sieben = new JButton("7");
        // btn_sieben.setLayout(null);
        btn_sieben.addActionListener(this);
        pn_zwei.add(btn_sieben);
        final JButton btn_acht = new JButton("8");
        // btn_acht.setLayout(null);
        btn_acht.addActionListener(this);
        pn_drei.add(btn_acht);
        final JButton btn_neun = new JButton("9");
        // btn_neun.setLayout(null);
        btn_neun.addActionListener(this);
        pn_drei.add(btn_neun);
        final JButton btn_punkt = new JButton(".");
        btn_punkt.addActionListener(this);
        btn_punkt.setBackground(Color.yellow);
        pn_drei.add(btn_punkt);
        final JButton btn_mal = new JButton("*");
        btn_mal.addActionListener(this);
        pn_vier.add(btn_mal);
        final JButton btn_div = new JButton("/");
        btn_div.addActionListener(this);
        pn_vier.add(btn_div);
        final JButton btn_plus = new JButton("+");
        btn_plus.addActionListener(this);
        pn_vier.add(btn_plus);
        final JButton btn_minus = new JButton("-");
        btn_minus.addActionListener(this);
        pn_vier.add(btn_minus);
        final JButton btn_sind = new JButton("=");
        btn_sind.addActionListener(this);
        pn_vier.add(btn_sind);
        pn_buttons.setBorder(BorderFactory.createEtchedBorder());
        // getContentPane().add(pn_buttons, BorderLayout.SOUTH);
        // edt_res.setText("eingabe");
        // pn_eins.setLayout(new BoxLayout(pn_eins, BoxLayout.X_AXIS));
        pn_eins.setBorder(BorderFactory.createEtchedBorder());
        pn_zwei.setBorder(BorderFactory.createEtchedBorder());
        pn_drei.setBorder(BorderFactory.createEtchedBorder());
        pn_vier.setBorder(BorderFactory.createEtchedBorder());
        getContentPane().add(pn_eins, BorderLayout.WEST);
        getContentPane().add(pn_zwei, BorderLayout.CENTER);
        getContentPane().add(pn_drei, BorderLayout.EAST);
        getContentPane().add(pn_vier, BorderLayout.SOUTH);
      }
    
      @Override
      public void actionPerformed(final ActionEvent event) {
        final String cmd = event.getActionCommand();
        final Object was = event.getSource();
        try {
          String name = was.toString();
          final int pos = name.indexOf("[");
          name = name.substring(0, pos);
          if (name.equals("javax.swing.JTextField")) {
            // JTextField neu <? extends Object> = was.getClass();
            ((JTextField) was).setText("ereignis");
          }
          if (name.equals("javax.swing.JButton")) {
            switch (cmd) {
              case "=":
                zahl2 = Float.valueOf(edt_res.getText());
                final Float resultat = calculate(zahl1, zahl2, operator);
                edt_res.setText(String.valueOf(resultat));
                break;
              case "/":
                operator = cmd;
                zahl1 = Float.valueOf(edt_res.getText());
                edt_res.setText("");
                break;
              case "*":
                operator = cmd;
                zahl1 = Float.valueOf(edt_res.getText());
                edt_res.setText("");
                break;
              case "+":
                operator = cmd;
                zahl1 = Float.valueOf(edt_res.getText());
                edt_res.setText("");
                break;
              case "-":
                operator = cmd;
                zahl1 = Float.valueOf(edt_res.getText());
                edt_res.setText("");
                break;
              default:
                String text = edt_res.getText();
                text += cmd;
                edt_res.setText(text);
            }
          }
          // PLAF-Klasse auswählen
          String plaf = "unknown";
          plaf = cmd;
          // LAF umschalten
          UIManager.setLookAndFeel(plaf);
          SwingUtilities.updateComponentTreeUI(this);
        } catch (final UnsupportedLookAndFeelException e) {
          System.err.println(e.toString());
        } catch (final ClassNotFoundException e) {
          System.err.println(e.toString());
        } catch (final InstantiationException e) {
          System.err.println(e.toString());
        } catch (final IllegalAccessException e) {
          System.err.println(e.toString());
        }
      }
    
      public void actFocusListener(final KeyListener event) {
        final Object was = ((EventObject) event).getSource();
        String name = was.toString();
        final int pos = name.indexOf("[");
        name = name.substring(0, pos);
        if (was.equals("javax.swing.JTextField")) {
          // JTextField neu <? extends Object> = was.getClass();
          ((JTextField) was).setText("focus!");
        }
      }
    
      private Float calculate(final Float eins, final Float zwei, final String command) {
        Float res = null;
    
        switch (command) {
          case "/":
            if (zwei != 0.0f) {
              res = eins / zwei;
            }
            break;
          case "*":
            res = eins * zwei;
            break;
          case "+":
            res = eins + zwei;
            break;
          case "-":
            res = eins - zwei;
            break;
        }
    
        return res;
    
      }
    }
    

    In Zukunft würde ich dir empfehlen mal ein Java Buch zu lesen an stelle das Forum zu bemühen.

    Gruss Renato



  • So etwas von Hand zu coden ist relativ übel. Benutze besser eine IDE mit eingebautem GUI-Editor, z.B. Netbeans. Die erzeugt dir gleich auch die nötigen Funktionen für die Button-Clicks, die du dann nur noch mit Leben füllen musst. 🙂



  • Ciao Andromeda

    Da magst du recht haben mit Netbeen. Aber ich bin der Meinung, befor man was automatisiert sollte man wissen was wie gemacht wird. Daher ist es nicht schlecht mal was von Hand zu machen. Auch wenn es doof ist.

    Gruss Renato