Swing组件的使用
主要讲解的知识为---------Swing组件------------使用
在 包javax.swing
1.Button
1.经常用到的按钮组件主要有以下4种形式:JButton , JToggleButton, JCCheckBox, JRadioButton
这些类均是 AbstractButton的子类或者间接子类
2.AbstractButton中定义了一些公有的方法:
有:addActionListener() , setEnabled() ,setText() , setIcon()
3.这四种按钮的使用,以以上共有的方法的具体使用,都将在Test***类中呈现、
1.1JButton
JButton 是最基本的一个按钮类型: 主要有的构造方法
1.JButton() --------创建一个既没有显示文本,也没有图标的按钮。
2.JButton(Icon icon)—创建一个既没有显示文本,但有图标的按钮。
3.JButton(String s)–创建有显示文本,也没有图标的按钮。
4.JButton(String s,Icon icon)–既有显示文本,又有图标
相应测试程序如下:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
// 以程序主要的内容: 通过不同按键,来回切换输出文本
// 用到的关键方法有 :setText() , setActionCommand() , setMnemonic()
public class TestJButton extends WindowAdapter implements ActionListener {
JFrame frame;
JPanel panel;
JButton button1,button2;
JTextField tf;
int tag=0;
public static void main(String[] args) {
TestJButton tes=new TestJButton();
tes.go();
}
public void go(){
frame=new JFrame("JButton example");
button1=new JButton("Sample");
button1.setMnemonic(KeyEvent.VK_S); // 设置命令快捷键(当执行程序时候,按下alt + s 即可触发事件): 无论 Shift
button1.setActionCommand("Sample"); // 设置命令名字
button1.addActionListener(this);
button2=new JButton("Disable Sample");
button2.setMnemonic(KeyEvent.VK_A); // 设置命令快捷键(当执行程序时候,按下alt + a 即可触发事件): 无论 Shift
button2.setActionCommand("disable");
button2.addActionListener(this);
// new 面板对象,并添加按钮组件
panel=new JPanel();
panel.add(button1);
panel.add(button2);
frame.getContentPane().add(panel,"South"); //获取内容窗格,并添加面板panel1到南部
tf=new JTextField(); //new 一个文本
tf.setBackground(Color.GREEN);
frame.getContentPane().add(tf,"Center");
frame.addWindowListener(this);// 添加 WindowListener监听程序
frame.setSize(300,150);
frame.setVisible(true);
}
// 实现ActionListener 接口中的 actionPerformed() 方法
public void actionPerformed(ActionEvent e){
String s1="You have pressed the Button";
String s2=" You do another time !";
//根据命令进行判断显示不同文本
if (e.getActionCommand()=="Sample"){
if (tag==0){
tf.setText(s1);
tag=1;
}
else {
tf.setText(s2);
tag=0;
}
}
if (e.getActionCommand()=="disable"){
button1.setEnabled(false); // 设置按钮不可用
button2.setText("Enable Sample");
button2.setActionCommand("enable");
}
if (e.getActionCommand()=="enable"){
button1.setEnabled(true); // 设置Sample按钮可用
button2.setText("Disable Sample");
button2.setActionCommand("disable");
}
}
//重载WindowAdapter类中的 windowClosing()方法
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
尚未更完,敬请期待!!