1

I have a program where I calculate for either 1 of 2 variables depending on the radio button selected. For some reason, isSelected() is not returning true or false. I will post my code below:

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

public class FutureValueFrame extends JFrame {
  public FutureValueFrame() {
    setTitle("Sample App");
    setSize(400,400);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}


public static void main(String[] args) {

    JFrame f = new FutureValueFrame();

    //GUI and BUTTONS
    JRadioButton monthlyRadioButton = new JRadioButton("Monthly Payment");
    JRadioButton loanAmountButton = new JRadioButton("Loan Amount");
    ButtonGroup selection = new ButtonGroup();
    selection.add(monthlyRadioButton);
    selection.add(loanAmountButton);

    JFormattedTextField loanAmountField = new JFormattedTextField(new DecimalFormat("####.##"));
    JFormattedTextField interestRateField = new JFormattedTextField(new DecimalFormat("####.##"));
    JFormattedTextField yearField = new JFormattedTextField(new DecimalFormat("####.##"));
    JFormattedTextField monthlyPaymentField = new JFormattedTextField(new DecimalFormat("####.##"));


    JPanel menuPanel = new JPanel();
    menuPanel.setLayout(new GridLayout(1,2));

    //ACTION LISTENER FOR RADIO BUTTONS
    monthlyRadioButton.addActionListener(new SelectionListener(monthlyRadioButton, loanAmountButton, loanAmountField, monthlyPaymentField));
    loanAmountButton.addActionListener(new SelectionListener(monthlyRadioButton, loanAmountButton, loanAmountField, monthlyPaymentField));

    JPanel topPanel = new JPanel();
    topPanel.setLayout(new GridLayout(1,2));
    topPanel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    topPanel.add(monthlyRadioButton);
    topPanel.add(loanAmountButton);

    JPanel botPanel = new JPanel();
    botPanel.setLayout(new GridLayout(4,2));

    botPanel.add(new JLabel("Loan Amount:"));
    botPanel.add(loanAmountField);

    botPanel.add(new JLabel("Yearly Interest Rate:"));
    botPanel.add(interestRateField);

    botPanel.add(new JLabel("Number of Years:"));
    botPanel.add(yearField);

    botPanel.add(new JLabel("Monthly Payment:"));
    botPanel.add(monthlyPaymentField);

    JPanel container = new JPanel();
    container.setLayout(new GridLayout(3,1));
    container.add(topPanel);
    container.add(botPanel);
    container.add(menuPanel);

    f.add(container);

    JButton calculateButton = new JButton("Calculate");

    if (monthlyRadioButton.isSelected()){
        calculateButton.addActionListener(new CalculateMonthlyListener(loanAmountField, interestRateField, yearField, monthlyPaymentField));
    }
    if (loanAmountButton.isSelected()){
        calculateButton.addActionListener(new CalculateLoanListener(loanAmountField, interestRateField, yearField, monthlyPaymentField));
    }

    JButton exitButton = new JButton("Exit");
    exitButton.addActionListener(new ExitListener());

    menuPanel.add(calculateButton);
    menuPanel.add(exitButton);     

    f.setVisible(true);
    f.setLocationRelativeTo(null);

    }

    class CalculateMonthlyListener implements ActionListener {

private JFormattedTextField loanAmountField;
private JFormattedTextField monthlyPaymentField;
private JFormattedTextField interestRateField;
private JFormattedTextField yearField; 
private float result;

 public CalculateMonthlyListener (JFormattedTextField loanAmountField, JFormattedTextField interestRateField, JFormattedTextField yearField, JFormattedTextField monthlyPaymentField)
{
  this.interestRateField = interestRateField;   
  this.yearField = yearField;
  this.loanAmountField = loanAmountField;
  this.monthlyPaymentField = monthlyPaymentField;
}

public void actionPerformed(ActionEvent event){

        monthlyPaymentField.setValue(new Double(12.22));
        System.out.println("You selected monthly");

}
}


class CalculateLoanListener implements ActionListener {

private JFormattedTextField loanAmountField;
private JFormattedTextField monthlyPaymentField;
private JFormattedTextField interestRateField; 
private JFormattedTextField yearField;
private float result;

public CalculateLoanListener (JFormattedTextField loanAmountField, JFormattedTextField interestRateField, JFormattedTextField yearField, JFormattedTextField monthlyPaymentField)
{
  this.interestRateField = interestRateField;   
  this.yearField = yearField;
  this.loanAmountField = loanAmountField;
  this.monthlyPaymentField = monthlyPaymentField;
}

public void actionPerformed(ActionEvent event){

   loanAmountField.setValue(new Double(12.22));

   System.out.println("You selected loan");



}
}

class ExitListener implements ActionListener {
public void actionPerformed(ActionEvent event){
    //f.dispose();
    System.exit(0);
    //System.out.println("You clicked exit");
}
}

class SelectionListener implements ActionListener {

private JRadioButton monthlyRadioButton;
private JRadioButton loanAmountButton;
private JFormattedTextField loanAmountField;
private JFormattedTextField monthlyPaymentField;


public SelectionListener (JRadioButton monthlyRadioButton, JRadioButton loanAmountButton, JFormattedTextField loanAmountField, JFormattedTextField monthlyPaymentField)
{
    this.monthlyRadioButton = monthlyRadioButton;   
    this.loanAmountButton = loanAmountButton;
    this.loanAmountField = loanAmountField;
    this.monthlyPaymentField = monthlyPaymentField;

}

public void actionPerformed(ActionEvent event){
      if(event.getSource() == monthlyRadioButton){
        loanAmountField.setEditable(false);
        monthlyPaymentField.setEditable(true);
      }
      else {
        monthlyPaymentField.setEditable(false);
        loanAmountField.setEditable(true);

      }
}
}



}

I believe the problem occurs at this snippet:

    if (monthlyRadioButton.isSelected()){
        calculateButton.addActionListener(new CalculateMonthlyListener(loanAmountField, interestRateField, yearField, monthlyPaymentField));
    }
    if (loanAmountButton.isSelected()){
        calculateButton.addActionListener(new CalculateLoanListener(loanAmountField, interestRateField, yearField, monthlyPaymentField));
    }

isSelected is not returning true. I've tried creating an int i and setting it to 1. I checked for i==1 in each condition and they executed correctly.

Any insights?

Jacob Schoen
  • 14,034
  • 15
  • 82
  • 102
Huy
  • 10,806
  • 13
  • 55
  • 99
  • 1
    First of all, never call swing/gui code off [EDT](http://en.wikipedia.org/wiki/Event_dispatching_thread). Use `SwingUtilities.invokeAndWait(Runnable)` inside your main method and put your gui code in the `Runnable`. Even if your code is just an example. – predi Jun 22 '12 at 06:48
  • What did you expect? The method simply returns false – Raffaele Jun 22 '12 at 06:50
  • See also [*How to Use Buttons, Check Boxes, and Radio Buttons*](http://docs.oracle.com/javase/tutorial/uiswing/components/button.html). – trashgod Jun 22 '12 at 07:32
  • 1
    *isSelected not returning true or false for JRadioButton* ... what returns it then ? Has Java introduced a 3-state boolean ? – Robin Jun 22 '12 at 08:19

3 Answers3

4

You should put selection checking code in a single action listener attached to your button, not decide which action listener to attach to the button based on the selection.

Replace the code you think is the source of your problem with this:

calculateButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if (selection.getSelection().equals(monthlyRadioButton.getModel())) {
             monthlyPaymentField.setValue(new Double(12.22));
            System.out.println("You selected monthly");
        } else {
            loanAmountField.setValue(new Double(12.22));
            System.out.println("You selected loan");
        }
    }
});

In order for this to compile you'll have to make the variables accessed in the above action listener final. Or replace both CalculateMonthlyListener and CalculateLoanListener with a single class which does the same as shown above.

Note that I did not use JRadioButton.isSelected() directly but instead used your ButtonGroup.getSelection(). You could also check the radio buttons themselves.

predi
  • 5,528
  • 32
  • 60
  • I tried using a single class and used your code as shown above. However, it still isn't updating my GUI field with the new values when I press calculate. – Huy Jun 25 '12 at 15:04
3
  • isSelected is fired from JRadioButton after ActionListener is done

then

  • use ItemListener (always fired twice) with to check for SELECTED / DESELECTED

and

  • put JRadioButtons to the ButtonGroup, ActionCommand returns String value
mKorbel
  • 109,525
  • 20
  • 134
  • 319
2

calculateButton has no assigned listener due to two things:

  1. At the beginning both radio buttons are not selected. Set one as selected then the proper calculateButton listener will be assigned in proper if statements.
  2. In actionPerformed method of SelectionListener you don't set a new calculateButton listener. Change that.
Adam Sznajder
  • 9,108
  • 4
  • 39
  • 60