我做了一个简单的计算器通过按钮GUI
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame implements ActionListener
{
GridLayout layout = new GridLayout(5, 1);
JLabel l1 = new JLabel("Number 1:");
JLabel l2 = new JLabel("Number 2:");
JLabel l3 = new JLabel("Answer:");
JTextField t1 = new JTextField(30);
JTextField t2 = new JTextField(30);
JTextField t3 = new JTextField(30);
JButton add = new JButton("+");
JButton sub = new JButton("-");
JButton mul = new JButton("*");
JButton div= new JButton("/");
Float ans;
public Calculator()
{
super("Calculator");
setSize(250, 200);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(add);
add(sub);
add(mul);
add(div);
setLayout(layout);
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
String n1 = t1.getText();
String n2 = t2.getText();
Float num1 = Float.parseFloat(n1);
Float num2 = Float.parseFloat(n2);
Object clicked = e.getSource();
if(add == clicked)
{
t3.setText(String.valueOf(num1+num2));
}
else if(sub == clicked)
{
t3.setText(String.valueOf(num1-num2));
}
else if(mul == clicked)
{
t3.setText(String.valueOf(num1*num2));
}
else
{
if(num2 == 0)
t3.setText("Can't Divide By Zero");
else
t3.setText(String.valueOf(num1/num2));
}
}
}
和A类阅读它
public class UseMyFrame
{
public static void main(String[] args)
{
Calculator calc = new Calculator();
calc.setVisible(true);
}
}
我的问题是我想补充另一个特点,并把9按钮1-9当按下时将它们各自的数字放在文本框中,但我不知道如何将它们设置为出现在文本框中,我首先想要set.text,但我意识到按钮如何知道在哪里把它的号码,因为如果我set.text我需要把它放在textfield1或textfield 2.我想让麻木er首先出现在textfield1中,然后在textfield2上(如果textfield1上已经有一个数字)
谢谢,我会尽力议员的建议,然后你的,如果它不适合我,非常感谢 – 2013-03-13 13:56:59