[英]How do I use the ActionEvent function with my code to do math equations
I have found out about the action event function recently, and I am really confused on how to make it so when I press 2 numbers and an operation it'll add/subtract/multiply/divide them. 我最近发现了动作事件函数,我对如何使它感到困惑,因此当我按2个数字和一个运算时,它将对它们进行加/减/乘/除运算。
Here is the menu that doesn't do anything yet: 这是尚未执行任何操作的菜单:
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();
}
}
You may use the following piece of code as example to get the sum of the two numbers: 您可以使用以下代码作为示例来获取两个数字的和:
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.