首页 > 解决方案 > 我想创建一个带有 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();
 }
}

标签: java

解决方案


这是使用两个不同动作侦听器的解决方案:

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 中显示结果。

当点击除法它划分数字。

在此处输入图像描述


推荐阅读