java怎么用图形界面编写一个随机产生四测运算
3个回答
展开全部
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.Serializable;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class NumberDemo extends JFrame implements Serializable {
private static final long serialVersionUID = 1L;
private JTextField jt1, jt2, jt3,jts[];
private JLabel jb1, jb2;
private JButton but;
private JPanel jp1;
private char chs[], count = 0;
private double n1, n2;
NumberDemo() {
chs = "+-X÷".toCharArray();
this.setTitle("随机运算小测试");
this.setBounds(300, 300, 350, 90);
this.setResizable(false);
init();
this.setDefaultCloseOperation(3);
this.setVisible(true);
}
private void init() {
jp1 = new JPanel(new FlowLayout());
jt1 = new JTextField(8);
jt2 = new JTextField(8);
jt3 = new JTextField(8);
jb1 = new JLabel("+");
jb2 = new JLabel("=");
but = new JButton("下一个");
myEvent();
jp1.add(jt1);
jp1.add(jb1);
jp1.add(jt2);
jp1.add(jb2);
jp1.add(jt3);
jp1.add(but);
this.add(jp1, BorderLayout.CENTER);
random();
}
private void myEvent() {
jts=new JTextField[3];
jts[0]=jt1;
jts[1]=jt2;
jts[2]=jt3;
for (int i = 0; i < jts.length; i++) {
jts[i].addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
e.consume();
}
});
}
but.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
random();
}
});
}
private void random() {
n1 = Double.parseDouble(getStr((Math.random() * 100 + 1)));
n2 = Double.parseDouble(getStr((Math.random() * 100 + 1)));
jt1.setText("" + n1);
count = (char) (Math.random() * 4);
jb1.setText(getAdd(count));
jt2.setText("" + n2);
switch (count) {
case 0:
jt3.setText(getStr(n1 + n2));
break;
case 1:
jt3.setText(getStr(n1 - n2));
break;
case 2:
jt3.setText(getStr(n1 * n2));
break;
default:
jt3.setText(getStr(n1 / n2));
break;
}
}
private String getStr(double tem) {
return String.format("%.3f", tem);
}
private String getAdd(int index) {
return chs[index] + "";
}
public static void main(String[] args) {
new NumberDemo();
}
}
2018-06-28 · 百度知道合伙人官方认证企业
关注
展开全部
可以在网上找到很好的模板进行学习,然后跟着进行敲出来。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
2018-06-28
展开全部
我可以帮你留下你的企蛾号
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询