Swing 是第二代GUI开发工具集,javax.swing包被列入Java的基础类库(JFC),Swing建立在AWT,Java2D,Accessibility等的基础上。与AWT相比,Swing具有更好的可移植性,提供了更完整的组件,增加了许多功能。
JTabbedPane
对于局CardLayout这种布局策略的一个不便之处是,用户不能了解被第一张卡片遮住的后面卡片的内容,JTabbedPane容器可以解决这个问题。
下例中使用JButton,ToolTipText,Border,Icon等,注意在容器JFrame及JApplet中加入组件要使用getContentPane().add()方法。
import java.awt.;
import java.awt.event.;
import javax.swing.;
import javax.swing.border.;
public class JButtonDemo extends JApplet{
JButton b1 = new JButton(“JButton 1”);
JButton b2 = new JButton(“JButton 2”);
JTextField t = new JTextField(20);
public void init() {
ActionListener a1 = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name =
((JButton)e.getSource()).getText();
t.setText(name+"Pressed");
}
};
b1.setToolTipText("Press Button will show msg");
b1.setBorder(new BevelBorder(BevelBorder.RAISED));
b1.setIcon(new ImageIcon("图像路径"));//设置图标
b1.addActionListener(a1);
b2.addActionListener(a1);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(b1);
getContentPane().add(b2);
getContentPane().add(t);
}
public static void main(String[] args) {
JApplet applet = new JButtonDemo();
JFrame frame = new JFrame("Test Swing");
frame.getContentPane().add(applet, BorderLayout.CENTER);
frame.setSize(400, 300);
applet.init();
applet.start();
frame.setVisible(true);
}
}
1.事件的概念:
事件处理是界面处理的基本功能,当用户点击鼠标或者按下键盘时,Swing界面上获得焦点的组件都会收到一个事件通知,这个事件通知是Swing体系内部发出的,界面就会根据收到的事件通知,做出相应的处理,比如弹出对话框或者读取用户输入。
2.事件处理流程:
(1)明确事件源(2)为事件源添加事件监听方法(3)事件处理:自定义事件处理类,实现对应的接口,实现该接口的抽象方法
1)事件源
所有的图形界面组件对象都可以成为事件源对象。
如何确定某一个组件是事件源对象?
动作发生在哪一个组件上,那么该组件就是一个事件源对象。
其实上边的代码中LoginActionListener就是一个事件处理类,它实现了鼠标监听器接口ActionListener,并实现了其抽象方法,代码如下
package cn.xwy.lesson131109;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
/**
- 鼠标事件处理类
- @author se7en
*/
//实现了鼠标事件监听器接口
public class LoginActionListener implements ActionListener {
private JComboBox login_num;
private JPasswordField password;
public LoginActionListener(JComboBox login_num,JPasswordField password){
this.login_num = login_num;
this.password = password;
}
//实现接口中的抽象方法
public void actionPerformed(ActionEvent e) {
String temp_login = (String)login_num.getSelectedItem();
String temp_password =(String) password.getText();
if(temp_login.equals(temp_password)){
JOptionPane.showMessageDialog(null,“登录成功!”);
}else{
JOptionPane.showMessageDialog(null,“账号或密码错误!!”);
}
}
}