0

I am new to java and creating a Simple gui App. In this simple app, I am trying to write a e-commerce letter for Firms. So, I planned my app something like this..

First i ask to user if he want to write an letter to British Firm or American. For this i use two radio buttons(one for american firm and second for british) and JButton. When user Trigger jbutton then i want to get radiobutton command(which type of letter user want to write).

The problem is I don't have any idea to get Radiobutton command when i trigger jButton. Please give me an Simple Idea(if possible with exapmle not complicated for begginers) to get RadioButtons value..

Here is my java Code:

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

class englet{

    static public JFrame f;
    static public JPanel p;
    static class getTypeOfLetter implements ActionListener{

        public void actionPerformed( ActionEvent e){
            String btnInput = e.getActionCommand();
            System.out.println(btnInput);

        }
    }
    public static void askletter(){
        JRadioButton btnRadio1;
        JRadioButton btnRadio2;
        ButtonGroup btngrp;
        JButton btnGo = new JButton("Write");
        btnRadio1 = new JRadioButton("Write Letter For American Firm");
        btnRadio1.setActionCommand("Amer");
        btnRadio2 = new JRadioButton("Write Letter For British Firm");
        btnRadio2.setActionCommand("Brit");
        btngrp    = new ButtonGroup();
        btnGo.setActionCommand("WriteTest");
        btnGo.addActionListener(new getTypeOfLetter());
        btngrp.add(btnRadio1);
        btngrp.add(btnRadio2);
        p.add(btnRadio1);
        p.add(btnRadio2);
        p.add(btnGo);
    }
    englet(){
        f  = new JFrame("English Letter");
        p  = new JPanel();
        askletter();
        f.add(p);
        f.setSize(400,200);
        f.setVisible(true);

    }
    public static void main (String[] argv ){
        englet i = new englet();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

I am using Notepad++ and CMD.. Not any another tools like netbeans initllli ecplisse. **RE-EDIT ** I want a possible solution and can satisfy me.. this app works but i am not able to get radiobuttons commmand with jubtton..

Phoenix404
  • 898
  • 1
  • 14
  • 29
  • The heuristic for NullPointerExceptions is almost always the same. **You should critically read your exception's stacktrace to find the line of code at fault, the line that throws the exception, and then inspect that line carefully**, find out which variable is null, and then trace back into your code to see why. You will run into these again and again, trust me. – Hovercraft Full Of Eels Feb 04 '16 at 17:42
  • but i ask this question to get a possible solution not fo error.. – Phoenix404 Feb 04 '16 at 17:43
  • In the future, post all exceptions as text to your question. It's easy to copy and paste the text from your cmd window. You'll also always want to indicate which lines throw the exception. – Hovercraft Full Of Eels Feb 04 '16 at 17:44
  • Only **you** know which line is throwing the exception -- again, look at the variables on that line and find out which are null. – Hovercraft Full Of Eels Feb 04 '16 at 17:44
  • Look at line 28 of your englet java class as the exception tells you. Also you will want to avoid use of static anything except for the main method. – Hovercraft Full Of Eels Feb 04 '16 at 17:45
  • sry there were miss understanding that was old error, my app works and only i am not able to get **JradioButton** actionCommand.. And i searched a lot this question on google.. i dont find it.. and this is not diplicate question of null expection.... **have you read this question or not ?** – Phoenix404 Feb 04 '16 at 17:49
  • this is 28 line `btnGo.addActionListener(new getTypeOfLetter());` i dont see any problem there.. – Phoenix404 Feb 04 '16 at 17:54
  • 1
    `Please give me an Simple Idea(if possible with exapmle not complicated for begginers) to get RadioButtons value` - did you read the JRadioButton API? You will find a link to the Swing tutorial on "How to use Radio Buttons", which contains a working example on how to test for the action command. The Swing tutorial is the first place you should look for examples. – camickr Feb 04 '16 at 20:36

1 Answers1

2

You've got several issues:

  • Over-use of static. Most of the fields and methods of your code should be non-static
  • You're missing key fields that will be necessary to transmit the information needed. To get the selected JRadioButton, you need to make JRadioButton fields and check which is selected, or (and my preference), you need to make the ButtonGroup variable a field and check which JRadioButton has been selected based on the ButtonModel returned by the ButtonGroup.

    You're currently using local variables and these won't be visible throughout the class, which is why either the JRadioButtons or the ButtonModel most be fields (declared in the class).

  • If you go with ButtonModel above, you must give each JRadioButton an appropriate actionCommand String.

For example:

import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class GetRadio extends JPanel {
    private static final String[] FIRMS = {"American Firm", "British Firm"};

    // You need this field to access it in your listener
    private ButtonGroup buttonGroup = new ButtonGroup();

    public GetRadio() {
        // create JButton and add ActionListener
        JButton button = new JButton("Select");
        button.addActionListener(new ButtonListener());

        // JPanel with a grid layout with one column and variable number of rows
        JPanel radioButtonPanel = new JPanel(new GridLayout(0, 1));
        radioButtonPanel.setBorder(BorderFactory.createTitledBorder("Select Firm")); // give it a title
        for (String firm : FIRMS) {
            // create radiobutton and set actionCommand
            JRadioButton radioButton = new JRadioButton(firm);
            radioButton.setActionCommand(firm);

            // add to button group and JPanel
            buttonGroup.add(radioButton);;
            radioButtonPanel.add(radioButton);
        }

        // add stuff to main JPanel
        add(radioButtonPanel);
        add(button);

    }

    private class ButtonListener implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // get button model of selected radio button from ButtonGroup
            ButtonModel model = buttonGroup.getSelection();

            // if null, no country selected
            if (model == null) {
                Component component = GetRadio.this;
                String message = "You must first select a country!";
                String title = "Error: No Country Selected";
                int type = JOptionPane.ERROR_MESSAGE;
                JOptionPane.showMessageDialog(component, message, title, type);
            } else {
                // valid country selected
                String country = model.getActionCommand();
                System.out.println("Letter to " + country);
            }
        }
    }

    private static void createAndShowGui() {
        GetRadio mainPanel = new GetRadio();

        JFrame frame = new JFrame("Get Radio Btn");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373