Bài 88: TextArea trong Java AWT

Ngày đăng: 1/2/2023 3:38:31 PM

Khai báo lớp AWT TextArea

1   

public class TextArea extends TextComponent


Ví dụ TextArea trong Java AWT

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23    

package vn.viettuts.awt;

 

import java.awt.Frame;

import java.awt.TextArea;

 

public class TextAreaExample1 {

 

    public TextAreaExample1() {

        Frame f = new Frame();

        TextArea area = new TextArea("Welcome to VietTuts.Vn "

                + "Ví dụ AWT TextArea");

        area.setBounds(20, 30, 300, 300);

        f.setTitle("Ví dụ AWT TextArea");

        f.add(area);

        f.setSize(400, 400);

        f.setLayout(null);

        f.setVisible(true);

    }

 

    public static void main(String args[]) {

        new TextAreaExample1();

    }

}

Kết quả:

Ví dụ TextArea trong Java AWT


Ví dụ TextArea 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    

package vn.viettuts.awt;

 

import java.awt.Button;

import java.awt.Frame;

import java.awt.Label;

import java.awt.TextArea;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

 

public class TextAreaExample2 extends Frame implements ActionListener {

    private Label label1, label2;

    private TextArea textArea;

    private Button button;

 

    public TextAreaExample2() {

        label1 = new Label();

        label1.setBounds(50, 50, 100, 30);

        label2 = new Label();

        label2.setBounds(160, 50, 100, 30);

        textArea = new TextArea();

        textArea.setBounds(20, 100, 300, 300);

        button = new Button("Count Words");

        button.setBounds(100, 400, 100, 30);

        button.addActionListener(this);

        add(label1);

        add(label2);

        add(textArea);

        add(button);

        setSize(400, 450);

        setLayout(null);

        setVisible(true);

    }

 

    @Override

    public void actionPerformed(ActionEvent e) {

        String text = textArea.getText();

        String words[] = text.split("\s");

        label1.setText("Words: " + words.length);

        label2.setText("Characters: " + text.length());

    }

 

    public static void main(String[] args) {

        new TextAreaExample2();

    }

}

Kết quả:

Ví dụ TextArea trong Java AWT

Nguồn tin: viettuts