今天我们要实作一个华氏摄氏的温度转换器,首先先来设计他的介面
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
public class BMI extends JFrame{
private final JLabel label1, label2, label3;
private final JTextField textField, textField2;
private final JButton btn;
public BMI(){
super("计算 BMI");
super.setLayout(null);
label1 = new JLabel("请输入体重(公斤):");
label1.setBounds(70, 70, 150, 20);
add(label1);
textField = new JTextField("0");
textField.setBounds(230, 70, 100, 20);
add(textField);
label2 = new JLabel("请输入身高(公尺):");
label2.setBounds(70, 120, 150, 20);
add(label2);
textField2 = new JTextField("0");
textField2.setBounds(230, 120, 100, 20);
add(textField2);
btn = new JButton("计算");
btn.setBounds(70, 170, 260, 20);
add(btn);
label3 = new JLabel("BMI:");
label3.setBounds(200, 2200, 100, 40);
add(label3);
}
}
import javax.swing.JFrame;
public class CalculateBMI {
public static void main(String[] args){
BMI bmi = new BMI();
bmi.setSize(400, 300); //设定宽,长
bmi.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //设定预设的关闭视窗
bmi.setVisible(true); //视窗预设是不可见的
}
}
接着我们要加入事件,事件处理机制有三部分:事件来源、事件物件和事件监听者。
每个 JComponent 都包含一个叫做 listenerList 的实体变数,指向 EventListenerList 类别的物件。每个 JComponent 子类别的物件,都会维护一个参照,指向他在 listenerList 中注册的监听者。
每个事件型别都有一个或数个对应到的事件监听者介面。当事件发生时, GUI 元件会收到一个独特的事件 ID,指出事件的型别。GUI 元件就会使用这个事件 ID,判定其事件应该要分派给哪个监听者型别,以及判定针对每个监听者物件,应该要呼叫哪一种方法。
以下列出几个事件类别、事件监听者介面和监听者介面所提供的事件处理者:
事件类别 | 监听者介面 | 监听者介面所提供的事件处理者 |
---|---|---|
ActionEvent | ActionListener | actionPerformed(ActionEvent e) |
ItemEvent | ItemListener | itemStateChanged(ItemEvent e) |
KeyEvent | KeyListener | keyTyped(KeyEvent e). keyPressed(KeyEvent e). keyReleased(KeyEvent e) |
MouseEvent | 1. MouseListener 2.MouseMotionListener | 1. mouseClicked(MouseEvent e) mouseEntered(MouseEvent e) mouseExited(MouseEvent e) mousePressed(MouseEvent e) mouseReleased(MouseEvent e) 2. mouseDragged(MouseEvente) mouseMoved(MouseEvent e) |
TextEvent | TextListener | textValueChanged(TextEvent e) |
WindowEvent | WindowListener | windowActivated(WindowEvent e) windowClosed(WindowEvent e) windowClosing(WindowEvent e) windowDeactivated(WindowEvent e) windowDeiconified(WindowEvent e) windowIconified(WindowEvent e) windowOpened(WindowEvent e) |
以下是元件可能触发事件类别的对应关系:
事件来源者 | 发生事件的类别型态 |
---|---|
JButton | ActionEvent |
JCheckBox | ActionEvent. ItemEvent |
JComponent | ComponentEvent. FocusEvent. KeyEvent. MouseEvent |
MenuItem | ActionEvent |
TextField | ActionEvent |
Window | WindowEvent |
以上是对事件的简单介绍,大家可以试试看在视窗上自己增加事件来完成这个程序,明天会公布我的写法供大家参考。
>>: 【14】如果不做图片标准化(Normalization)会怎麽样
在Day 20有稍微提到中断机制,我们稍微深入说明一下,中断其实也是种不浪费资源的方式,如果处理器一...
在了解了独立表格空间的基本结构後,系统表格空间就好了解多了,基本上很类似,但系统表格空间需要纪录一些...
接下来的测试将会需要用到 mocking 的 library ,在 Android 大家比较常用的是...
运算子 所谓的运算子就是就是一些符号,运算广义来说就是对资料做的任何动作。 平常生活中的加减乘除是一...
昨天我们建立了一个新的 Angular 专案,然後跑了一下内建的范例程序,今天我们要来动手加入一些自...