java - 我想创建一个带有 3 个文本字段和 2 个按钮的 JAVA 窗口
问题描述
我想创建一个带有 3 个文本字段和 2 个按钮的简单 Java 窗口。我希望按钮执行从用户输入的减法和除法运算。在 if-else 条件下,我需要 actionPerformed 方法的帮助。我不知道在 if-else 括号中写什么条件。
我写了以下代码:
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;
class Event extends Frame implements ActionListener
{
TextField tf, tf1, tf2;
Event()
{
tf=new TextField();
tf.setBounds(60,50,170,20);
tf1=new TextField();
tf1.setBounds(60,70,170,20);
tf2=new TextField();
tf2.setBounds(60,90,170,20);
Button b=new Button("Subtraction");
b.setBounds(100,120,80,30);
b.addActionListener(this);
Button b1=new Button("Division");
b1.setBounds(100,160,80,30);
b1.addActionListener(this);
add(b);
add(b1);
add(tf);
add(tf1);
add(tf2);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(ActionListener(Subtraction))
{
int a,b,c;
Scanner sc=new Scanner(System.in);
a=sc.nextInt();
tf.setText("Enter first value: "+a);
b=sc.nextInt();
tf1.setText("Enter second value: "+b);
c=b-a;
tf2.setText("Result is: "+ c);
}
else
{
int d,f,g;
Scanner sc= new Scanner(System.in);
d=sc.nextInt();
tf.setText("Enter first value: "+d);
f=sc.nextInt();
tf1.setText("Enter second value: "+f);
g=d/f;
tf2.setText("Result is: "+g);
}
}
public static void main(String args[])
{
new Event();
}
}
解决方案
这是使用两个不同动作侦听器的解决方案:
import java.awt.*;
import java.awt.event.*;
public class Event extends Frame {
TextField tf, tf1, tf2;
Event()
{
tf=new TextField();
tf.setBounds(60,50,170,20);
tf1=new TextField();
tf1.setBounds(60,70,170,20);
tf2=new TextField();
tf2.setBounds(60,90,170,20);
Button b=new Button("Subtraction");
b.setBounds(100,120,80,30);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int num1 = Integer.parseInt(tf.getText());
int num2 = Integer.parseInt(tf1.getText());
tf2.setText(Integer.toString(num1 - num2));
}
});
Button b1=new Button("Division");
b1.setBounds(100,160,80,30);
b1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int num1 = Integer.parseInt(tf.getText());
int num2 = Integer.parseInt(tf1.getText());
tf2.setText(Integer.toString(num1 / num2));
}
});
add(b);
add(b1);
add(tf);
add(tf1);
add(tf2);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[])
{
new Event();
}
}
当您单击减法时,它会减去文本框 1 和文本框 2 中的数字,并在文本框 3 中显示结果。
当点击除法它划分数字。
推荐阅读
- c# - Asp.net Core 如何记录 System.AccessViolationException
- jquery - 使用 laravel 在 ajax requast 发送的多个元素上循环
- javascript - 无法读取空函数问题的属性“值”
- php - 付款方式选项卡自定义 OpenCart
- installation - 是否可以在不使用 *.DLL 库的情况下创建启动画面来显示 PNG 图像?
- c# - ML .NET 图像分类 - 我可以在默认 MLNET 训练中使用字节数组而不是文件路径来预测图像吗?
- python - JSONDecodeError:期望值:第 1 行第 1 列(char 0,json.loads
- java - 谷歌云平台推送订阅发送重复消息 ID 字段
- javascript - 传单:无法在按钮中显示图标
- git - 有没有办法让 VS 代码提交并推动关闭?