突然发现昨天还漏了,还有一种其他布局管理器
GridBagLayout布局管理器:基于网格
SpringLayout布局管理器
使用布局管理器,可以满足日常的普遍需求,也可以不使用布局管理器(有点MFC那味)
setLayout(NULL), 不使用布局管理器
setBounds(int x,int y,int width,int height)使用数值来设置组件位置
不可见组件(占位置,或者间隔)
public static Component creatHorizontalGlue();
public static component createVerticalGlue();
public static component createHorizontalStruct(int width);
public static component createVerticalStruct(int height);
public static component createRigidArea(Dimension d);
事件发生时,所有相关的方法都会被调用
比如说,点击事件包含右击事件
且执行顺序无法确定
MouseEvent类
KeyEvent类
…
每一种事件,对应一个监听程序接口,它指定该种事件的处理方法
为了接受处理某类事件,必须注册事件监听程序
// Actionevent事件,对应ActionListener监听程序
public interface ActionListener extends EventListener {
// 当Actionevent事件发生,以下方法会被调用
public void ActionPerformed(Actionevent E)
}
每个组件都有许多 addXXXListener(XXXLisener)的方法,为组件注册事件监听程序
JButton类的一个方法
public void addActionListener(addActionListener l)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import org.w3c.dom.events.EventListener;
public class a {
public static void main(String[] args) {
JFrame frame1 = new JFrame("this is test ");
JButton b1 = new JButton("this is button");
// 注册监听类
b1.addActionListener(new ButtonEvent());
// 窗口的布局
frame1.getContentPane().add(b1, BorderLayout.CENTER);
frame1.setSize(100, 100);
frame1.setVisible(true);
}
}
class ButtonEvent implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("test of event");
}
}
第二种方法:从组件类继承,再定义注册事件方法
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import org.w3c.dom.events.EventListener;
public class a {
public static void main(String[] args) {
JFrame frame1 = new JFrame("this is test ");
ExternsTest b1 = new ExternsTest("this is button");
// 窗口的布局
frame1.getContentPane().add(b1, BorderLayout.CENTER);
frame1.setSize(100, 100);
frame1.setVisible(true);
}
}
// 注意继承的是按钮
class ExternsTest extends JButton implements ActionListener {
// 重载构造函数
public ExternsTest(String text) {
super(text);
// 为本类型添加监听方法
addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
System.out.println("this is test");
}
}
监听多类事件
多加几个
addActionListener(this);侦听方法
部分方法被调用,会将事件信息打包成一个结构体
例如调用,mouseFragged()方法被调用,会得到一个MouseEvent类型参数
事件适配器
就是一个类中有多个监听方法,你继承后不得不一个个实现
为了只对要处理的事件方法进行编写
只需要继承一下接口适配器即可
示例
class MouseClickHandler extends MouseInputAdapter {
// 这里只对MouseClicked事件处理
public void MouseClicked(MouseEvent e) {
System.out.println("this is test");
}
}



