您的位置:首页 > 其它

事件处理,ActionLister、ActionEvent(求一个数的平方)

2018-02-06 15:33 459 查看
Example6.java文件:

public class Example6 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
WindowNumber win = new WindowNumber();
}

}
WindowNumber.java文件:

import java.awt.*;

import javax.swing.*;

public class WindowNumber extends JFrame{
JTextField textInput,textShow;
PoliceListen listener;
public WindowNumber(){
init();
setBounds(100,100,150,150);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
void init() {
// TODO Auto-generated method stub
setLayout(new FlowLayout());
textInput = new JTextField(10);
textShow = new JTextField(10);
textShow.setEditable(false);
listener = new PoliceListen();
listener.setJTextField(textShow);//将textShow引用传递给listen的text
textInput.addActionListener(listener);//textInput是事件源,listener是监视器
add(textInput);
add(textShow);
}
}
PoliceListen.java文件:

import java.awt.event.*;

import javax.swing.*;

public class PoliceListen implements ActionListener {
JTextField text;
public void setJTextField(JTextField text){
this.text = text;
}
public void actionPerformed(ActionEvent e){
int n =0,m = 0;
JTextField textSource = (JTextField)e.getSource();
String str = textSource.getText();
if(!str.isEmpty()){
try{
n = Integer.parseInt(str);
m = n*n;
//System.out.print(m);
text.setText(""+m);
}
catch(Exception ee){
textSource.setText("请输入数字");
}
}
}
}
效果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐