Bài 87: TextField trong Java AWT

Ngày đăng: 1/2/2023 3:35:49 PM

Khai báo lớp AWT TextField

1      

public class TextField extends TextComponent


Ví dụ TextField trong Java AWT

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20    

package vn.viettuts.awt;

 

import java.awt.Frame;

import java.awt.TextField;

 

public class TextFieldExample1 {

    public static void main(String args[]) {

        Frame f = new Frame("TextField Example");

        TextField t1, t2;

        t1 = new TextField("Welcome to VietTuts.Vn");

        t1.setBounds(50, 100, 200, 30);

        t2 = new TextField("Vi du AWT TextFiled");

        t2.setBounds(50, 150, 200, 30);

        f.add(t1);

        f.add(t2);

        f.setSize(400, 250);

        f.setLayout(null);

        f.setVisible(true);

    }

}

Kết quả:

Ví dụ TextField trong Java AWT


Ví dụ TextField trong Java AWT với ActionListener

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43    

44

45

46

47

48

49

50

51

52

53

54

55

package vn.viettuts.awt;

 

import java.awt.Button;

import java.awt.Frame;

import java.awt.TextField;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

 

public class TextFieldExample2 extends Frame implements ActionListener {

    TextField textField1, textField2, textField3;

    Button button1, button2;

 

    TextFieldExample2() {

        textField1 = new TextField();

        textField1.setBounds(50, 50, 150, 20);

        textField2 = new TextField();

        textField2.setBounds(50, 100, 150, 20);

        textField3 = new TextField();

        textField3.setBounds(50, 150, 150, 20);

        textField3.setEditable(false);

        button1 = new Button("+");

        button1.setBounds(50, 200, 50, 50);

        button2 = new Button("-");

        button2.setBounds(120, 200, 50, 50);

        button1.addActionListener(this);

        button2.addActionListener(this);

        add(textField1);

        add(textField2);

        add(textField3);

        add(button1);

        add(button2);

        setSize(300, 300);

        setLayout(null);

        setVisible(true);

    }

 

    public void actionPerformed(ActionEvent e) {

        String s1 = textField1.getText();

        String s2 = textField2.getText();

        int a = Integer.parseInt(s1);

        int b = Integer.parseInt(s2);

        int c = 0;

        if (e.getSource() == button1) {

            c = a + b;

        } else if (e.getSource() == button2) {

            c = a - b;

        }

        String result = String.valueOf(c);

        textField3.setText(result);

    }

 

    public static void main(String[] args) {

        new TextFieldExample2();

    }

}

Kết quả:

Ví dụ TextField trong Java AWT

Nguồn tin: viettuts