Sunday, June 24, 2012

ActionListener of JRadioButton

Example of using JRadioButton ActionListener:

ActionListener of JRadioButton


package javatestswing;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JFrameWin extends JFrame{
    
    public JFrameWin(){
        
        final JPanel jPanel = new JPanel();
        
        this.setTitle("java-buddy.blogspot.com");
        this.setSize(500, 400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         
        JButton buttonExit = new JButton(" Exit ");
        buttonExit.addActionListener(new ActionListener(){
 
            @Override
            public void actionPerformed(ActionEvent ae) {
                System.exit(0);
            }
        });
        
        final JRadioButton jRadioButtonA = new JRadioButton("JRadioButton A");
        final JRadioButton jRadioButtonB = new JRadioButton("JRadioButton B");
        final JRadioButton jRadioButtonC = new JRadioButton("JRadioButton C");

        ActionListener radioButtonActionListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                JOptionPane.showMessageDialog(
                        JFrameWin.this, ae.getActionCommand());
            }
            
        };
        
        jRadioButtonA.addActionListener(radioButtonActionListener);
        jRadioButtonB.addActionListener(radioButtonActionListener);
        jRadioButtonC.addActionListener(radioButtonActionListener);
        
        ButtonGroup buttonGroup  = new ButtonGroup();
        buttonGroup.add(jRadioButtonA);
        buttonGroup.add(jRadioButtonB);
        buttonGroup.add(jRadioButtonC);
        
        Box verticalBox = Box.createVerticalBox();
        verticalBox.add(jRadioButtonA);
        verticalBox.add(jRadioButtonB);
        verticalBox.add(jRadioButtonC);
        
        jPanel.add(verticalBox);
        jPanel.add(buttonExit);
        
        this.add(jPanel);
        
    }
}


1 comment:

  1. ActionListener radioButtonActionListener = new ActionListener() es una interfaz, así que no puedes crear un objeto de ella, primero tiene que implementarla en otra clase y crear un objeto de esa clase

    ReplyDelete