簡體   English   中英

如何在代碼中使用ActionEvent函數來執行數學方程式

[英]How do I use the ActionEvent function with my code to do math equations

我最近發現了動作事件函數,我對如何使它感到困惑,因此當我按2個數字和一個運算時,它將對它們進行加/減/乘/除運算。

這是尚未執行任何操作的菜單:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

@SuppressWarnings("serial")
public class Window extends JFrame implements ActionListener {

    @SuppressWarnings("unused")
    public static void main (String[] args) {
            Window em = new Window();
    }

    public Window() {
        setTitle("testing");
        setSize(800,600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(new GridLayout(4,6,3,3));
        setResizable(false);


    JButton button1= new JButton("7");
    JButton button2= new JButton("8");
    JButton button3= new JButton("9");
    JButton button10= new JButton("+");
    JButton button4= new JButton("4");
    JButton button5= new JButton("5");
    JButton button6= new JButton("6");
    JButton button11= new JButton("-");
    JButton button7= new JButton("1");
    JButton button8= new JButton("2");
    JButton button9= new JButton("3");
    JButton button12= new JButton("*");
    JButton button0= new JButton("0");
    JButton buttonR= new JButton("Reset");
    JButton buttonE= new JButton("Enter");
    JButton button13= new JButton("÷");

    JTextField x = new JTextField();
    JTextField y = new JTextField();
    JTextField CPP_entry = new JTextField();

    CPP_entry.setEditable(false);      

    add(button1);
    add(button2);
    add(button3);
    add(button10);
    add(new JLabel("    x:")); 
    add(x); 
    add(button4);
    add(button5);
    add(button6);
    add(button11);
    add(new JLabel("    y:")); 
    add(y); 
    add(button7);
    add(button8);
    add(button9);
    add(button12);
    add(new JLabel("    x/y:")); 
    add(CPP_entry); 
    add(buttonR);
    add(button0);
    add(buttonE);
    add(button13);
    setVisible(true);
}

public void actionPerformed(ActionEvent e) {
    JButton currentButton = (JButton)e.getSource();
    }
}

您可以使用以下代碼作為示例來獲取兩個數字的和:

public double first;
public double sum;

private void method() {
    JTextField field = new JTextField();
    JButton plus = new JButton("+");
    plus.addActionListener(e -> {
        first = Double.parseDouble(field.getText());
    });

    JButton result = new JButton("=");
    result.addActionListener(e -> {
        sum = first + Double.parseDouble(field.getText());
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM