Thursday, June 21, 2012

Java Swing example: place elements in vertical

I want to modify last article "Example of using Swing ButtonGroup" to place the JRadioButton(s) in vertically. It can be done easily with javax.swing.Box.

place elements in vertical


JFrameWin.java
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");
        
        JButton buttonReadRadio = new JButton(" Read Radio Buttons ");
        buttonReadRadio.addActionListener(new ActionListener(){
 
            @Override
            public void actionPerformed(ActionEvent ae) {
                String radioSetting = "";
                
                if (jRadioButtonA.isSelected()){
                    radioSetting += "jRadioButtonA is selected.\n";
                }
                if (jRadioButtonB.isSelected()){
                    radioSetting += "jRadioButtonB is selected.\n";
                }
                if (jRadioButtonC.isSelected()){
                    radioSetting += "jRadioButtonC is selected.\n";
                }
                
                JOptionPane.showMessageDialog(JFrameWin.this, radioSetting);
            }
        });
        
        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(buttonReadRadio);
        jPanel.add(buttonExit);
        
        this.add(jPanel);
        
    }
}


No comments:

Post a Comment