Sabtu, 31 Agustus 2013

Radio Button Java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class DemoRadioButton implements ItemListener {
  public JLabel label1, label2;
  public JRadioButton radioButton1, radioButton2, radioButton3;
  public ButtonGroup bg;

  public DemoRadioButton() {
    label1 = new JLabel("IDE Java yang Anda sukai:");
    label1.setLocation(10, 10);
    label1.setSize(label1.getPreferredSize());

    label2 = new JLabel("Pilihan Anda: (belum ada pilihan)");
    label2.setLocation(10, 115);
    label2.setSize(label2.getPreferredSize());

    radioButton1 = new JRadioButton("Eclipse");
    radioButton1.setLocation(10, 25);
    radioButton1.addItemListener(this);
    radioButton1.setSize(radioButton1.getPreferredSize());
   
    radioButton2 = new JRadioButton("Netbeans");
    radioButton2.setLocation(10, 50);
    radioButton2.addItemListener(this);
    radioButton2.setSize(radioButton2.getPreferredSize());
   
    radioButton3 = new JRadioButton("JBuilder");
    radioButton3.setLocation(10, 75);
    radioButton3.addItemListener(this);
    radioButton3.setSize(radioButton3.getPreferredSize());  
   
    // menentukan group dari semua item
    bg = new ButtonGroup();
    bg.add(radioButton1);
    bg.add(radioButton2);
    bg.add(radioButton3);
  }

  public void createAndShowGUI() {
    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Demo JRadioButton");
    frame.setLayout(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(label1);
    frame.getContentPane().add(radioButton1);
    frame.getContentPane().add(radioButton2);
    frame.getContentPane().add(radioButton3);
    frame.getContentPane().add(label2);

    frame.setBounds(0, 0, 300, 200);
    frame.setLocationRelativeTo(null);

    frame.setVisible(true);
  }

  public void itemStateChanged(ItemEvent event) {
    JRadioButton rb = (JRadioButton) event.getSource();
    label2.setText("Pilihan Anda: " + rb.getText());
  }

  public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        DemoRadioButton app = new DemoRadioButton();
        app.createAndShowGUI();
      }
    });
  }
}

0 komentar: