0
我是java programming的新手。我想执行一个任务,当按下按钮时,即从附加代码的JFrame中显示0-9时,该按钮的值必须被分配给在按下按钮之前选择的JField。如何操作?从按钮中获取文本到选定的文本域
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class calci2 extends JFrame implements ActionListener {
JFrame f1;
JPanel p;
JButton b[] = new JButton[10];
JButton btnadd;
JButton btnmul;
JButton btndiv;
JButton btnsub;
public static JTextField t1;
JTextField t2;
JTextField t3;
JLabel no1;
JLabel no2;
JLabel res;
calci2() {
f1 = new JFrame();
p = new JPanel();
t1 = new JTextField(15);
t2 = new JTextField(15);
t3 = new JTextField(15);
no1 = new JLabel("Enter 1st number");
no2 = new JLabel("Enter 2nd number");
res = new JLabel(" Result is ");
btnadd = new JButton("ADD");
btnmul = new JButton("MUL");
btndiv = new JButton("DIV");
btnsub = new JButton("SUB");
for (int i = 0; i < 10; i++) {
b[i] = new JButton("" + i);
}
btnadd.addActionListener(this);
btnmul.addActionListener(this);
btndiv.addActionListener(this);
btnsub.addActionListener(this);
for (int i = 0; i < 10; i++) {
b[i].addActionListener(this);
}
p.add(no1);
p.add(t1);
p.add(no2);
p.add(t2);
p.add(res);
p.add(t3);
p.add(btnadd);
p.add(btnmul);
p.add(btndiv);
p.add(btnsub);
for (int i = 0; i < 10; i++) {
p.add(b[i]);
}
this.add(p);
}
public static void main(String args[]) {
calci2 c = new calci2();
c.setDefaultCloseOperation(EXIT_ON_CLOSE);
c.setSize(300, 300);
c.setVisible(true);
c.setResizable(false);
c.setLocationRelativeTo(null);
}
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
String s1 = new String(t1.getText());
String s2 = new String(t2.getText());
String s3 = new String();
int a = Integer.parseInt(s1);
int b = Integer.parseInt(s2);
if (str.equals("ADD")) {
int c = a + b;
s3 = String.valueOf(c);
t3.setText(s3);
}
else if (str.equals("SUB")) {
int c = a - b;
s3 = String.valueOf(c);
t3.setText(s3);
}
else if (str.equals("MUL")) {
int c = a * b;
s3 = String.valueOf(c);
t3.setText(s3);
}
else if (str.equals("DIV")) {
int c = a/b;
s3 = String.valueOf(c);
t3.setText(s3);
}
}
};
感谢ü!!!!这么多萨拉你的帮助....但只是一个疑问更多 - 我想添加按钮的值,即点击时,0-9,最近选定的用户textfield,而不是使用t1.setText ...值应实现在textfield按下按钮之前选择。这是我的第一篇文章,我会再次小心缩进我的代码,以便其他人可以很容易地理解..这次忍受..谢谢你 – Omkar
没关系,现在答案编辑再次检查,,,和URW –
是的,它为我工作..再次感谢。 – Omkar