常用布局
1)、流布局:
FlowLayout 从左到右,自上而下方式在容器中排列,控件的大小不会随容器大小变化.
容器.setLayout(new FlowLayout(FlowLayout.LEFT));
2)、网格布局:
GridLayout 按照指定行数与列数,将容器分成大小相等的单元格每个单元格放置一个控件. 不能将控件放在指定单元格
容器.setLayout(new GridLayout(3,4,10,15));
3)、边界布局:
BorderLayout 将容器分成东、西、南、北、中五个部分
容器.setLayout(new BorderLayout());
窗口的内容面板默认布局就是边界布局。
容器.add(控件,BorderLayout.NORTH);
4)、混合布局:
使用JPanel,将多个布局组合在一起使用
5)、绝对布局 null:
以坐标定位
容器.setLayout(null);
每个控件在放置在容器之前,必须设置其边界 setBounds(x,y,width,height);
btn.setBounds(10,100,30,60);
常用事件
1)、事件源 EventSource:能够触发事件控件 如:JButton,JTextField,JFrame,JComboBox,....
2)、事件 Event:ActionEvent,KeyEvent,WindowEvent,TextEvent,...
3)、事件侦听者Listener(接口) ActionListener,WindowListener,...
class A implements ActionListener{
public void actionPerformed(ActionEvent e){
....
}
}
A lis=new A();
4)、事件处理函数
public void actionPerformed(ActionEvent e){
....
}
事件流程:事件源触发事件-->事件源侦听者接收事件-->自动调用相应事件处理函数.
实践编程
1.在应用程序窗体中安排1个文本框,一个标签。在文本框输入一个数字(0-9),按回车键,在标签处显示对应的英文单词。 0---zero,1---one,....
窗体类:
package简单数字对应窗体;import java.awt.*;import java.awt.event.*;import javax.swing.*;public class Numcompare extendsJFrame{
JTextField text;
JLabel label;
Numcompare(){
setTitle("Number change");//限制输入一个数字
text=new JTextField(10);
label=newJLabel();
label.setText("请输入0-9的数字");
text.addActionListener(newActionListener() {public voidactionPerformed(ActionEvent e) {
String getstr=text.getText();
String showstr=null;switch(getstr) {case "0":
showstr="zero";break;case "1":
showstr="one";break;case "2":
showstr="two";break;case "3":
showstr="three";break;case "4":
showstr="four";break;case "5":
showstr="five";break;case "6":
showstr="six";break;case "7":
showstr="seven";break;case "8":
showstr="eight";break;case "9":
showstr="nine";break;default:
showstr=("请输入0-9的数字");break;
}
label.setText(showstr);
text.setText(null);
}
});
setLayout(newFlowLayout());
add(text);
add(label);
setBounds(100,100,460,190);
setVisible(true);
validate();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);;
}
}
实现类(注:以下省略实现类--实例化自定义窗体)
package简单数字对应窗体;public classtest {public static voidmain(String[] args) {newNumcompare();
}
}
结果: