我运行此脚本,当我单击添加时,它可以工作并添加 2 个框,但是当我单击任何其他按钮时,它不会打开带有答案的框。我不知道为什么消息框没有打开其中任何一个的答案,但添加的任何人都可以解释并告诉我修复。编码:
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;
public class Gui extends JFrame{
private JButton reg;
private JButton reg2;
private JButton reg3;
private JButton reg4;
private JTextField text;
private JTextField text2;
private JTextField text3;
private JTextField text4;
private JTextField text5;
private JTextField text6;
private JTextField text7;
private JTextField text8;
public Gui(){
super("Buttons");
setLayout(new FlowLayout());
text = new JTextField(20);
text2 = new JTextField(20);
text3 = new JTextField(20);
text4 = new JTextField(20);
text5 = new JTextField(20);
text6 = new JTextField(20);
text7 = new JTextField(20);
text8 = new JTextField(20);
reg = new JButton("Add");
reg2 = new JButton("Divide");
reg3 = new JButton("Multiply");
reg4 = new JButton("Subtract");
add(text);
add(text2);
add(reg);
add(text3);
add(text4);
add(reg2);
add(text5);
add(text6);
add(reg3);
add(text7);
add(text8);
add(reg4);
handlerClass handler = new handlerClass();
reg.addActionListener(handler);
reg2.addActionListener(handler);
reg3.addActionListener(handler);
reg4.addActionListener(handler);
}
public class handlerClass implements ActionListener{
public void actionPerformed(ActionEvent event){
String st = text.getText();
String st2 = text.getText();
String st3 = text.getText();
String st4 = text.getText();
String st5 = text.getText();
String st6 = text.getText();
String st7 = text.getText();
String st8 = text.getText();
int txt1 = Integer.parseInt(st);
int txt2 = Integer.parseInt(st2);
int txt3 = Integer.parseInt(st3);
int txt4 = Integer.parseInt(st4);
int txt5 = Integer.parseInt(st5);
int txt6 = Integer.parseInt(st6);
int txt7 = Integer.parseInt(st7);
int txt8 = Integer.parseInt(st8);
if(event.getActionCommand()=="Add"){
int add=txt1+txt2;
JOptionPane.showMessageDialog(null, String.format("Answer: %s", add));
}
if(event.getActionCommand()=="Divide"){
if(txt4>0){
int add2=txt3/txt4;
JOptionPane.showMessageDialog(null, String.format("Answer: %s", add2));
}else{
JOptionPane.showMessageDialog(null, String.format("Cannot divide by zero"));
}
}
if(event.getActionCommand()=="Multiply"){
int add3=txt5*txt6;
JOptionPane.showMessageDialog(null, String.format("Answer: %s", add3));
}
if(event.getActionCommand()=="Subtract"){
int add4=txt7-txt8;
JOptionPane.showMessageDialog(null, String.format("Answer: %s", add4));
}
}
}
}