1

This is my code:

    panel2.add(question1);
    panel2.add(true1);
    panel2.add(false1);
    panel2.add(labelAnswer1);
    panel2.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    if(true1.isSelected()) {
        labelAnswer1.setText("You are CORRECT!");
    }

    else if(false1.isSelected()) {
        labelAnswer1.setText("You are wrong. The correct answer is " + true1.getText());
    }

    else if(true1.isSelected() && false1.isSelected()) {
        labelAnswer1.setText("You cannot select two answers!");
    }

Not really sure what I'm doing wrong. Might just be too late at night, haha. Any help would be appreciated. Thanks and best regards!

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
acheema_
  • 7
  • 1

3 Answers3

4

Swing, like most GUI frameworks is event driven, that is, something happens and then you respond to it. You don't known when or in what order those events might occur.

Instead, you use "listeners" (aka a Observer Pattern) to register interest with your components, which tell you when something happens and you take appropriate action based on the current state of your program

Take a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners for more details

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.anchor = GridBagConstraints.WEST;

            add(new JLabel("Is a banna:"), gbc);

            ButtonGroup bg = new ButtonGroup();
            ActionListener listener = new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String cmd = e.getActionCommand();
                    System.out.println("You guessed " + cmd);
                    if ("Yellow".equalsIgnoreCase(cmd)) {
                        JOptionPane.showMessageDialog(TestPane.this, cmd + " is the answer");
                    } else {
                        JOptionPane.showMessageDialog(TestPane.this, cmd + " is not the answer");
                    }
                }
            };
            add(createGuess("Red", listener, bg), gbc);
            add(createGuess("Green", listener, bg), gbc);
            add(createGuess("Blue", listener, bg), gbc);
            add(createGuess("Yellow", listener, bg), gbc);
        }

        protected JRadioButton createGuess(String guess, ActionListener listener, ButtonGroup bg) {
            JRadioButton btn = new JRadioButton(guess);
            btn.addActionListener(listener);
            bg.add(btn);
            return btn;
        }

    }

}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

You should add more code so we can see where your listeners are, other components, etc.

Your if statements should be in a listener. Right now, the code executes right after you add in the elements to the page, and no other time. So, this code only happens right after elements are added, before the user has time to select an element. Also, what if no elements are selected? Then no if statement is hit, and for that reason you may need to add an else statement.

This setup should be that you have two radio buttons, a question, and a button the user hits when they have selected their answer. That button should have a listener that runs the above if statements.

Matt C
  • 4,470
  • 5
  • 26
  • 44
-2

Got it figured out.

Added this:

true1.addMouseListener(this);

And this:

@Override
public void mouseClicked(MouseEvent e) {
    if (e.getSource() == true1) {
        labelAnswer1.setText("You are CORRECT!");
    }
}

Thanks for all the help!

William Price
  • 4,033
  • 1
  • 35
  • 54
acheema_
  • 7
  • 1
  • 3
    No, you should NEVER add a `MouseListener` to a button, buttons can be activated by the user through the use of a key event or programmatically, which trigger a `ActionEvent` – MadProgrammer May 30 '15 at 04:25
  • 2
    This is a very bad solution -- never use a MouseListener for this. If the button is inactivated for instance, the MouseListener will still be active, and this is not user-expected behavior. – Hovercraft Full Of Eels May 30 '15 at 04:36
  • Please consider a different solution. – Matt C May 30 '15 at 19:25