import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.WindowAdapter
import java.awt.event.WindowEvent
import java.util.Random
public class JiaFaQi {
Frame f
Label l1, l2
TextField tf
Button b1, b2
int a1, a2
JiaFaQi() {
f = new Frame("1位数加法")
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0)
}
})
f.setBounds(100, 100, 210, 100)
f.setLayout(new FlowLayout())
generateProblem()
l1 = new Label(getProblem()/*"2+6="*/)
l2 = new Label("答案在此!")
tf = new TextField(10)
b1 = new Button("答案判断")
b2 = new Button("重新来")
b1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
if (Integer.parseInt(tf.getText()) == (a1 + a2)) {
l2.setText("正确")
return
}
} catch (Exception e) {}
l2.setText("错误")
}
})
b2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
generateProblem()
l1.setText(getProblem())
l2.setText("答案在此!")
tf.setText("")
}
})
f.add(l1)
f.add(tf)
f.add(b1)
f.add(l2)
f.add(b2)
f.setVisible(true)
}
Random random = new Random()
void generateProblem() {
a1 = random.nextInt(10)
a2 = random.nextInt(10)
}
String getProblem() {
return a1 + "+" + a2 + "="
}
public static void main(String args[]) {
new JiaFaQi()
}
}
这个也太简单了,你写一个main方法,public static void main(String args[]){
//这里写你的awt类的程序
}
然后把你写的awt类的程序放到mian方法里面,
然后点击右键--》run as-->Java Application 就OK了
这个就是布局设置,使用不同的layout实现,这个你应该知道的吧,有flowlayout,grouplayout,borderlayout等。我给你个建议,你可以使用一些图形界面设计可视化插件,比较有名的像jigloo。你只要拖拉控件就可以了,他有默认的布局格式,你也可以选择,就像选word图片环绕方式一样,比较方便。当然有的IDE直接支持可视化,像NETBEANS。
另外awt是java比较老的图形界面制作包,你可以看下api文档,基本上很多东西都不用了,现在有个包是javax.swing,里面都是对awt包的发展,像JButton这种。
_____________________________________________________
我觉得我讲得已经很清楚了,第一,panel是一个试图,在上面加控件就必须要设置布局;第二,如果你不使用这些控件,你就会很蛋疼,在那边搞布局要搞半天。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)