一、实验目的
- 掌握组件的概念与用法
- 掌握布局管理器的概念与用法。
实验内容:
必做
-
练习课上学习的GUI基本布局,熟悉相关java语句。
-
编程实现一个加法计算器的布局,如下图所示。
-
第8章第7题。
实验解答
1.加法计算器
package ex12;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Totalizer extends JFrame implements ActionListener {
//继承了Frame,该类本身就是一个窗口。可用this替代创建面板
JTextField t1,t2,t3;
JButton b;
JLabel label1,label2;
public Totalizer(){
//窗口标题
super("plus games!!");
//Container c = getContentPane();
//c.setLayout(new FlowLayout(FlowLayout.LEFT));
this.setLayout(null);
label1 = new JLabel("加法运算:");
label1.setBounds(10,30, 70, 30);
t1 = new JTextField();
t1.setBounds(70, 30, 50, 30);
label2 = new JLabel("+");
label2.setBounds(130,30,50,30);
t2 = new JTextField();
t2.setBounds(150, 30, 50, 30);
b = new JButton("=");
b.setBounds(210, 30, 50, 30);
//ActionListener al = new ActionListener();
t3 = new JTextField();
t3.setBounds(270, 30, 50, 30);
this.add(label1);
this.add(t1);
this.add(label2);
this.add(t2);
this.add(b);
this.add(t3);
//关闭方式:点击关闭按钮
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//设置大小
setSize(450,150);
//设置可见
setVisible(true);
//不可调节窗口大小
this.setResizable(false);
//给按钮b注册监听者this
b.addActionListener(this);
}
public static void main(String[] args) {
//创建对象
new Totalizer();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==b) {
// 如果事件源是b按钮
if (!this.t1.getText().matches("[0-9.-]+")) {
JOptionPane.showMessageDialog(getParent(),"请输入要计算的数字!");
t1.requestFocus();
}
else if (!this.t2.getText().matches("[0-9.-]+")) {
JOptionPane.showMessageDialog(getParent(),"请输入要计算的数字!");
t2.requestFocus();
}
else
{
String a=this.t1.getText(),b=this.t2.getText(),c;
double one,two,sum;
one =Double.parseDouble(a);
two=Double.parseDouble(b);
sum=one+two;
c=String.valueOf(sum);
this.t3.setText(c);
// 标签setText
}
}
}
}
运行结果:
2.第8章第7题。
package ex12;
import javax.swing.*;
import java.awt.*;
public class Button extends JFrame{
public Button() {
super("按钮布局");
setVisible(true);
//setResizable(false);
setBounds(100,100,230,230);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this.setLayout(null);
setLayout(new GridLayout(3, 1)); // 3行1列
//创建6个按钮
JButton b1,b2,b3,b4,b5,b6; ;
//分别给按钮起名字
b1= new JButton("1");
b2= new JButton("2");
b3= new JButton("3");
b4= new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
//第一个面板
JPanel p1=new JPanel();//
p1.setLayout(new FlowLayout(FlowLayout.CENTER,20,20));
p1.add(b1);
p1.add(b2);
p1.add(b3);
add(p1);
//第二个面板
JPanel p2=new JPanel();
p2.add(b4);
p2.setLayout(new FlowLayout(FlowLayout.CENTER,20,20));
add(p2);
//第三个面板
JPanel p3=new JPanel();
p3.setLayout(new FlowLayout(FlowLayout.CENTER,20,20));
p3.add(b5);
p3.add(b6);
add(p3); // JFrame默认边界布局
}
//主程序
public static void main(String[] args) {
new Button();
}
}
运行结果:
实验总结:
学习了swing界面设计与按钮布局。