java窗口实验 (1)

package chuangkou;

import java.awt.*;
import java.awt.event.*;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Computer1 extends JFrame implements ActionListener {
	int x, y, z;
	JLabel label1, label2, label3;
	JTextField text1, text2, text3;
	Button buttonGetNumber, buttonEnter;

	Computer1(String s) {
		super(s);
		setLayout(new FlowLayout());
		buttonGetNumber = new Button("获取题目");
		text1 = new JTextField(10);
		label2 = new JLabel("+");
		text2 = new JTextField(10);
		label1 = new JLabel("=");
		text3 = new JTextField(10);
		buttonEnter = new Button("确认答案");
		buttonEnter.addActionListener(this);
		buttonGetNumber.addActionListener(this);
		label3 = new JLabel(" ");
		
		add(buttonGetNumber);
		add(text1);
		add(label2);
		add(text2);
		add(label1);
		add(text3);
		add(buttonEnter);
		add(label3);

		setBounds(100, 100, 500, 150);
		setVisible(true);
		validate();
	}

	public void actionPerformed(ActionEvent e)
	{
		if (e.getSource() == buttonGetNumber)
		{
			x = (int) (Math.random() * 100) + 1;
			y = (int) (Math.random() * 100) + 1; // 为x和y赋值
			text1.setText(String.valueOf(x));
			text2.setText(String.valueOf(y));
		} else if (e.getSource() == buttonEnter) 
		{
			z = Integer.parseInt(text1.getText())
					+ Integer.parseInt(text2.getText());
			if (text3.getText().length() == 0)
			{
				label3.setText("请输入答案");
			}

			else if (Integer.parseInt(text3.getText()) == z) 
			{
				label3.setText("你回答正确");
			} else
			{
				label3.setText("你回答错误");
			}
		}
	}
}


上机感言:窗口很好玩   争取早点把”画图“小软件做出来。。

java窗口实验 (1)_第1张图片

你可能感兴趣的:(java窗口实验 (1))