Creating JRadioButton: Text, Icons, and Initial Selection State
Creating JRadioButton: Text, Icons, and Initial Selection State
Creating JRadioButton: Text, Icons, and Initial Selection State
इस लेख में हम step-by-step समझेंगे कि कैसे आप Java Swing में high-quality radio buttons बना सकते हैं।
हम focus रखेंगे text, icons और initial selection state पर ताकि exam या project में clear, usable UI बन सके।
Overview
JRadioButton Swing का एक component है जो users को एक option चुनने देता है।
जब आप multiple options देते हो, तो उन्हें एक ButtonGroup में रखा जाता है ताकि सिर्फ़ एक option selected रहे।
Why use JRadioButton?
Radio buttons तब use होते हैं जब choice mutually exclusive हो — जैसे gender, payment method या exam options।
JRadioButton simple, accessible और keyboard-friendly होता है, इसलिए UI design में common choice है।
Basic Example
सबसे पहले एक simple example देखें जो text वाले radio buttons बनाता है और initial selection set करता है।
ये code एक minimal Swing frame बनाता है जहा radio buttons दिखाई देंगे।
import javax.swing.*;
import java.awt.*;
public class RadioDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Creating JRadioButton: Text, Icons, and Initial Selection State");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JRadioButton r1 = new JRadioButton("Option A");
JRadioButton r2 = new JRadioButton("Option B");
JRadioButton r3 = new JRadioButton("Option C");
// Initial selection
r2.setSelected(true);
// Grouping
ButtonGroup group = new ButtonGroup();
group.add(r1); group.add(r2); group.add(r3);
panel.add(r1); panel.add(r2); panel.add(r3);
frame.add(panel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
Key points in the Basic Example
setSelected(true) से आप initial selection define करते हो।
ButtonGroup जरूरी है ताकि multiple JRadioButton में से सिर्फ़ एक ही selected रहे।
Adding Icons to JRadioButton
Text के साथ icon जोड़ने से UI ज्यादा visual और user-friendly बनता है।
ImageIcon use करके आप normal, selected और disabled icons set कर सकते हो।
JRadioButton r = new JRadioButton("Save");
ImageIcon normal = new ImageIcon("icons/save.png");
ImageIcon selected = new ImageIcon("icons/save-selected.png");
r.setIcon(normal);
r.setSelectedIcon(selected);
r.setToolTipText("Save your work");
Tips for Icons
- Icon size लगभग 16x16 या 24x24 रखें ताकि layout टूटे नहीं।
- Transparent PNG use करें ताकि background से blend हो जाए।
- setDisabledIcon() भी set करें ताकि look consistent रहे जब button disabled हो।
Layout and Spacing
Radio buttons को अच्छा दिखाने के लिए proper layout manager चुनें — FlowLayout, BoxLayout या GridBagLayout।
Spacing के लिए setBorder(BorderFactory.createEmptyBorder(...)) या Box.createRigidArea useful रहता है।
Example with Icons and Layout
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
JRadioButton r1 = new JRadioButton("Small");
r1.setIcon(new ImageIcon("icons/small.png"));
r1.setSelectedIcon(new ImageIcon("icons/small-selected.png"));
r1.setAlignmentX(Component.LEFT_ALIGNMENT);
panel.add(r1);
panel.add(Box.createRigidArea(new Dimension(0,8)));
Initial Selection Strategies
Initial selection user experience में बड़ा role निभाता है — sensible default चुनना चाहिए।
Default often depends on context: most common choice, last saved choice, या safe option चुनें।
Programmatic vs. Persisted Initial State
Programmatic initial state code-level setSelected(true) से आता है और तुरंत apply होता है।
Persisted state के लिए आप preferences, config file या database में last choice save करके उसे load कर सकते हैं।
Example: Persisting Selection with Preferences
import java.util.prefs.Preferences;
Preferences prefs = Preferences.userRoot().node("app/radioDemo");
String saved = prefs.get("preferredOption", "B"); // default B
r1.setSelected("A".equals(saved));
r2.setSelected("B".equals(saved));
r3.setSelected("C".equals(saved));
// on change:
prefs.put("preferredOption", "A");
Accessibility and Mnemonics
Accessibility बढ़ाने के लिए mnemonic और accessible description add करो।
Mnemonic से keyboard से selection आसान होता है — जैसे Alt+S से select करना।
r.setMnemonic(KeyEvent.VK_S); // Alt+S to select
r.getAccessibleContext().setAccessibleDescription("Select this option to save");
Event Handling: ActionListener & ItemListener
जब user radio button change करे तो event handle करने के लिए ActionListener use होता है।
ItemListener भी option change track करने के लिए useful है, खासकर state-specific logic के लिए।
r.addActionListener(e -> {
String cmd = ((JRadioButton)e.getSource()).getActionCommand();
System.out.println("Selected: " + cmd);
});
r.setActionCommand("OptionA");
ButtonModel और isSelected()
ButtonModel से आप detailed state पढ़ सकते हो — जैसे selected, armed या pressed।
isSelected() method simple check है जो current selection बताता है।
ButtonModel model = r.getModel();
boolean selected = model.isSelected();
if (r.isSelected()) {
// do something
}
Styling and Look & Feel
UIManager का use करके look and feel change कर सकते हो, ताकि radio buttons platform-consistent दिखें।
Default icon या spacing कभी-कभी LAF पर निर्भर करते हैं — इसलिए testing अलग OS पर ज़रूरी है।
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(frame);
Keyboard Navigation and Focus
Radio buttons को tab-order और arrow keys से navigate किया जा सकता है।
Focus traversal policy set करके advanced behavior control कर सकते हो।
Error Handling and Disabled State
अगर कोई option invalid हो तो setEnabled(false) करके उसे disable करो।
Disable होने पर user को tooltip या small message से बताओ कि क्यों disabled है।
Example: Conditional Disable
if (!configAvailable) {
r.setEnabled(false);
r.setToolTipText("Option not available because configuration is missing");
r.setDisabledIcon(new ImageIcon("icons/disabled.png"));
}
Grouping & Nested Groups
ButtonGroup में add करने से mutual exclusivity मिलती है पर visual grouping के लिए JPanel use करो।
Nested groups तब बनते हैं जब कुछ choices sub-category में हों — separate ButtonGroup बनाओ।
Example: Nested Radio Groups
JPanel paymentPanel = new JPanel();
JRadioButton card = new JRadioButton("Card");
JRadioButton upi = new JRadioButton("UPI");
ButtonGroup payGroup = new ButtonGroup();
payGroup.add(card); payGroup.add(upi);
paymentPanel.add(card); paymentPanel.add(upi);
JPanel cardPanel = new JPanel();
JRadioButton visa = new JRadioButton("Visa");
JRadioButton master = new JRadioButton("MasterCard");
ButtonGroup cardGroup = new ButtonGroup();
cardGroup.add(visa); cardGroup.add(master);
cardPanel.add(visa); cardPanel.add(master);
Internationalization (i18n)
Text hard-code मत करो; ResourceBundle use करो ताकि translation फिर आसान हो।
Radio button labels और tooltips resources से load करो और UI update करो locale change पर।
Example: ResourceBundle
ResourceBundle rb = ResourceBundle.getBundle("messages", Locale.getDefault());
JRadioButton r = new JRadioButton(rb.getString("option.save"));
r.setToolTipText(rb.getString("tooltip.save"));
Performance Considerations
Radio buttons lightweight होते हैं, पर अगर बहुत सारे items हों तो virtualization पर ध्यान दो।
Large icon images या heavy listeners UI sluggish कर सकते हैं — images optimize करो।
Testing & Debugging
Always test keyboard-only navigation, screen reader compatibility और different LAFs पर behavior।
Edge cases: multiple groups accidentally overlapping, duplicate action commands, या missing icons।
Common Pitfalls and Fixes
- Buttons not exclusive — ensure you added them to the same ButtonGroup.
- Icon not showing — check path और classpath if using resources inside jar.
- Initial selection ignored — ensure setSelected called before frame visibility or update UI after change.
Table: Useful Methods & Properties
| Method / Property | Purpose |
|---|---|
setSelected(boolean) |
Initial या runtime selection set करता है |
setIcon(Icon) |
Normal icon set करने के लिए |
setSelectedIcon(Icon) |
Selected state का icon define करने के लिए |
setDisabledIcon(Icon) |
Disabled दिखाने के लिए icon |
setMnemonic(int) |
Keyboard shortcut assign करने के लिए |
setActionCommand(String) |
Action event में meaningful command भेजने के लिए |
getModel() |
ButtonModel से low-level state access |
Design Patterns and Best Practices
MVC pattern follow करो — UI code simple रखो, logic controller में रखें।
ActionCommand और centralized ActionListener से event handling clean रहता है।
Example: Centralized Action Handling
ActionListener listener = e -> {
String cmd = e.getActionCommand();
switch(cmd) {
case "SAVE": doSave(); break;
case "LOAD": doLoad(); break;
}
};
rSave.setActionCommand("SAVE");
rLoad.setActionCommand("LOAD");
rSave.addActionListener(listener);
rLoad.addActionListener(listener);
Use Cases and Examples
Exam application में: question type select करने के लिए radio buttons use करो (MCQ, True/False)।
Settings pane में: theme select, language select या default behavior choose करने के लिए ideal है।
Accessibility Checklist
- Labels visible और meaningful हों।
- Keyboard shortcut (mnemonic) defined हो।
- Accessible description provide करें।
- High contrast और scalable icons test करें।
Packaging Icons inside JAR
Resource path use करके icons load करें — getResource() method reliable होता है।
Example: new ImageIcon(getClass().getResource("/icons/save.png")) jar-friendly है।
Advanced: Custom Painting and Look
अगर default radio button style change करना हो तो custom Icon implement कर सकते हो।
Custom painting में performance और accessibility ध्यान में रखना जरूरी है।
Icon custom = new Icon() {
public void paintIcon(Component c, Graphics g, int x, int y) {
// draw circle and dot based on selection
}
public int getIconWidth() { return 16; }
public int getIconHeight() { return 16; }
};
r.setIcon(custom);
r.setSelectedIcon(customSelected);
Debugging Resource Paths
Icons नहीं आ रहे हैं तो getResource() null return कर सकता है — path सही है या नहीं चेक करो।
IDE में resource folder को classpath में add करना मत भूलो, और jar में भी path check करो।
Checklist before Release
- Default selection sensible है और documented है।
- All icons optimized और bundled हैं।
- Keyboard navigation और accessibility pass हुआ है।
- All strings ResourceBundle में हैं (i18n ready)।
Small Utility: Create Radio Button Factory
बार-बार code से बचने के लिए utility method बनाओ जो text, icon और actionCommand ले कर JRadioButton return करे।
public static JRadioButton createRadio(String text, String iconPath, String cmd, boolean selected) {
JRadioButton r = new JRadioButton(text);
if (iconPath != null) r.setIcon(new ImageIcon(MyClass.class.getResource(iconPath)));
r.setActionCommand(cmd);
r.setSelected(selected);
return r;
}
Final Implementation Tips
Testing अलग अलग screen sizes और DPI पर करो ताकि icons और text अच्छे दिखें।
Logging add करो ताकि selection changes traceable हों और user issues जल्दी fix हो सकें।