第二次用 mvc架构写GUI java程序,写的好不熟练啊~~ 3天木有看java ,知识点都忘完了。
上代码和照片
贴代码:
Main.java
public class Main { public static void main(String args[]){ Window window=new Window(); window.setBounds(100, 100, 500, 130); window.setVisible(true); } }
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Window extends JFrame implements ActionListener{ //利用窗口做监视器 /** * */ private static final long serialVersionUID = 1L; Sum sum; // model Number generateNumber=new Number(); //model JTextField text1,text2,text3; //view JButton getProblem,checkAnswer; //contrller JLabel answer; //view Window(){ init(); setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } void init(){ sum=new Sum(); text1=new JTextField(10); text2=new JTextField(10); text1.setEditable(false); text2.setEditable(false); text3=new JTextField(10); answer=new JLabel("你还没回答呢!"); getProblem=new JButton("获取题目"); getProblem.addActionListener(this); checkAnswer=new JButton("确认答案"); checkAnswer.addActionListener(this); setLayout(new FlowLayout()); add(getProblem); add(text1); add(new JLabel("+")); add(text2); add(new JLabel("=")); add(text3); add(checkAnswer); add(answer); } public void actionPerformed(ActionEvent e){ if(e.getSource()==checkAnswer){ int a,b,c; a=Integer.parseInt(text1.getText()); b=Integer.parseInt(text2.getText()); c=Integer.parseInt(text3.getText()); sum.set(a, b); if(c==sum.answer()){ answer.setText("答对了"); text3.setText(""); } if(c!=sum.answer()){ answer.setText("答错了"); text3.setText(""); } } if(e.getSource()==getProblem){ text1.setText(String.valueOf(generateNumber.getNumber()) ); text2.setText(String.valueOf(generateNumber.getNumber()) ); answer.setText("你还没回答呢!"); } } }Number.java
public class Number { private int a; public int getNumber(){ a=(int)(Math.random()*100)+1; return a; } }sum.java
public class Sum { private int a,b,c; public void set(int a,int b){ this.a=a; this.b=b; } public int answer(){ c=a+b; return c; } }