Bài 86: Label trong Java AWT

Ngày đăng: 1/2/2023 3:33:10 PM

Khai báo lớp AWT Label

1     

public class Label extends Component implements Accessible 


Ví dụ Label 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.Label;

 

public class LabelExample1 {

    public static void main(String args[]) {

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

        Label l1, l2;

        l1 = new Label("First Label.");

        l1.setBounds(5010010030);

        l2 = new Label("Second Label.");

        l2.setBounds(5015010030);

        f.add(l1);

        f.add(l2);

        f.setSize(400200);

        f.setLayout(null);

        f.setVisible(true);

    }

}

Kết quả:

Ví dụ Label trong Java AWT


Ví dụ Label 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.TextField;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

 

public class LabelExample2 extends Frame implements ActionListener {

    private TextField textField;

    private Label label;

    private Button button;

 

    public LabelExample2() {

        textField = new TextField();

        textField.setBounds(505015020);

        label = new Label();

        label.setBounds(5010025020);

        button = new Button("Find IP");

        button.setBounds(501506030);

        button.addActionListener(this);

        add(button);

        add(textField);

        add(label);

        setSize(400200);

        setLayout(null);

        setVisible(true);

    }

 

    @Override

    public void actionPerformed(ActionEvent e) {

        try {

            String host = textField.getText();

            String ip = java.net.InetAddress.getByName(host).getHostAddress();

            label.setText("IP of " + host + " is: " + ip);

        catch (Exception ex) {

            System.out.println(ex);

        }

    }

 

    public static void main(String[] args) {

        new LabelExample2();

    }

}

Kết quả:

Ví dụ Label trong Java AWT

Nguồn tin: viettuts