Bài 91: Choice trong Java AWT

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

Khai báo lớp AWT Choice

1     

public class Choice extends Component implements ItemSelectable, Accessible


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

24

25

package vn.viettuts.awt;

 

import java.awt.Choice;

import java.awt.Frame;

 

public class ChoiceExample1 {

    public ChoiceExample1() {

        Frame frame = new Frame("Ví dụ Java AWT Choice");

        Choice choice = new Choice();

        choice.setBounds(100, 100, 150, 150);

        choice.add("C++");

        choice.add("Java");

        choice.add("PHP");

        choice.add("Python");

        choice.add("C#");

        frame.add(choice);

        frame.setSize(400, 250);

        frame.setLayout(null);

        frame.setVisible(true);

    }

 

    public static void main(String args[]) {

        new ChoiceExample1();

    }

}

Kết quả:

Ví dụ Choice trong Java AWT


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

package vn.viettuts.awt;

 

import java.awt.Button;

import java.awt.Choice;

import java.awt.Frame;

import java.awt.Label;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

 

public class ChoiceExample2 {

    public ChoiceExample2() {

        Frame frame = new Frame("Ví dụ Java AWT Choice");

        final Label label = new Label();

        label.setAlignment(Label.CENTER);

        label.setSize(400, 100);

        Button button = new Button("Show");

        button.setBounds(200, 100, 50, 20);

        final Choice choice = new Choice();

        choice.setBounds(100, 100, 75, 75);

        choice.add("C++");

        choice.add("Java");

        choice.add("PHP");

        choice.add("Python");

        choice.add("C#");

        frame.add(choice);

        frame.add(label);

        frame.add(button);

        frame.setSize(400, 250);

        frame.setLayout(null);

        frame.setVisible(true);

        button.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                String data = "Ngôn ngữ lập trình được chọn: " +

                        choice.getItem(choice.getSelectedIndex());

                label.setText(data);

            }

        });

    }

 

    public static void main(String args[]) {

        new ChoiceExample2();

    }

}

Kết quả:

Ví dụ Choice trong Java AWT

Nguồn tin: viettuts