Contoh Program RadioButton di Java

Contoh Program sederhana berikut ini mencoba menampilkan inputan RadioButton dengan menggunakan Java. Class yang digunakan adalah JRadioButton. Di dalam program juga dicontohkan penanganan event dengan ItemListener.

Berikut ini tampilannya:
contoh-program-radiobutton-java

Berikut ini programnya:

01 import java.awt.*;
02
03 import java.awt.event.*;
04 import javax.swing.*;
05
06 public class RadioButtonTest extends JFrame {
07
08 private JTextField text;
09 private Font plainFont, boldFont, italicFont;
10 private JRadioButton plainButton, boldButton, italicButton;
11 private ButtonGroup radioGroup;
12
13 public RadioButtonTest() {
14 super ("Mencoba Radio button");
15
16 Container container = getContentPane();
17 container.setLayout(new FlowLayout());
18
19 text = new JTextField ("Lab. Bahasa Pemrograman 3", 20);
20 text.setHorizontalAlignment(SwingConstants.CENTER);
21 container.add(text);
22
23 plainButton = new JRadioButton ("Plain", true);
24 container.add(plainButton);
25
26 boldButton = new JRadioButton ("Bold", false);
27 container.add(boldButton);
28
29 italicButton = new JRadioButton ("Italic", false);
30 container.add(italicButton);
31
32 radioGroup = new ButtonGroup();
33 radioGroup.add(plainButton);
34 radioGroup.add(boldButton);
35 radioGroup.add(italicButton);
36
37 plainFont = new Font ("Verdana",Font.PLAIN, 14);
38 boldFont = new Font ("Verdana",Font.BOLD, 14);
39 italicFont = new Font ("Verdana",Font.ITALIC, 14);
40 text.setFont(plainFont);
41
42 plainButton.addItemListener(new RadioButtonHandler (plainFont));
43 boldButton.addItemListener(new RadioButtonHandler (boldFont));
44 italicButton.addItemListener(new RadioButtonHandler (italicFont));
45
46 setSize (300,100);
47 setLocationRelativeTo(null);
48 setVisible(true);
49 }
50
51 public static void main (String args[]) {
52 RadioButtonTest test = new RadioButtonTest();
53 test.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
54 }
55
56 //inner class
57 private class RadioButtonHandler implements ItemListener {
58
59 private Font font;
60
61 public RadioButtonHandler (Font f) {
62 font = f;
63 }
64
65 public void itemStateChanged (ItemEvent e) {
66 text.setFont(font);
67 }
68
69 } //end of inner class
70
71 } //end of outer class

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: