10月13日学习日志
今天用java swing编写了小学生出题的判断界面。
代码为:
package math15; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTextField; public class math15 extends JFrame implements ActionListener{ int n=0,m=0; JLabel jlresult=new JLabel(""); JLabel jlquestion[]= new JLabel[10]; JLabel jlAnswer[]= new JLabel[10]; JLabel jlTotal= new JLabel( "共10题" ); JLabel jlcorrect[]= new JLabel[10]; JTextField jtf[]= new JTextField[10]; JButton jb1= new JButton( "评卷" ); JPanel jp1= new JPanel(); JPanel jp2= new JPanel(new GridLayout(5,2)); String[] question= new String[10]; String [] answer= new String [10]; math15(){ super ( "算数运算测试" ); for(int i=0;i<10;i++) { jtf[i]=new JTextField(3); jlquestion[i]=new JLabel(""); jlAnswer[i]=new JLabel(""); jlcorrect[i]= new JLabel(); } jlTotal.setFont( new Font( null ,Font.PLAIN, 20 )); for(int i=0;i<10;i++) { jtf[i].setFont( new Font( null ,Font.PLAIN, 20 )); jlAnswer[i].setFont( new Font( null ,Font.PLAIN, 20 )); jlquestion[i].setFont( new Font( null ,Font.PLAIN, 20 )); jlcorrect[i].setFont( new Font( null ,Font.PLAIN, 20 )); jlcorrect[i].setForeground(Color.RED); } Question(); jb1.addActionListener( this ); jp1.add(jlTotal);jp1.add(jb1);jp1.add(jlresult); for(int i=0;i<10;i++) { jp2.add(jlquestion[i]);jp2.add(jtf[i]);jp2.add(jlcorrect[i]);jp2.add(jlAnswer[i]); } add(jp1,BorderLayout.NORTH); add(jp2,BorderLayout.CENTER); setSize(1000,500); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo( null ); setVisible( true ); } public void actionPerformed(ActionEvent ae) { if(ae.getSource()==jb1) { for(int i=0;i<10;i++) { jlquestion[i].setText(question[i]); jlAnswer[i].setText( "答案:"+answer[i] ); if(jtf[i].getText().trim().equals(answer[i])) { jlcorrect[i].setText("√"); n++; } else { jlcorrect[i].setText("×"); m++; } jtf[i].setEnabled( true ); } jlresult.setText("正确"+n+"个,错误"+m+"个,共"+10*n+"分"); } } public static void main(String[] args) { new math15(); } public void Question() { int a,b,c; for(int i=0;i<10;i++){ a=(int)(Math.random()*100+1); b=(int)(Math.random()*100+1); c=(int)(Math.random()*2)+1; if(c==1)answer[i]=String.valueOf(a+b); if(c==2)answer[i]=String.valueOf(a-b); if(c==1)question[i]=String.valueOf(a)+"+"+String.valueOf(b)+"="; if(c==2)question[i]=String.valueOf(a)+"-"+String.valueOf(b)+"="; } for(int i=0;i<10;i++) { jlquestion[i].setText(question[i]); } } }
运行结果为: