将JRadioButton转换为布尔值?

时间:2014-12-22 18:01:27

标签: java radio-button boolean project

我试图制作它,以便根据是否按下单选按钮,它将使用Java图形并创建一个带有预设图形的小程序。虽然我试图使用if语句,但它告诉我我不能将JRadioButton转换为布尔值,但我觉得这不是正确的方法。我拉我的头发因为我不明白怎么做。

帮助/指导将不胜感激:D!谢谢 !

我的代码如下所示:

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


public class RadioButton extends JPanel {

    static JFrame frame;

   JLabel pic;
   RadioListener myListener = null;
   public RadioButton() {



       // Create the radio buttons and assign Keyboard shortcuts using Mnemonics
       JRadioButton displacement = new JRadioButton("Displacement");
       displacement.setMnemonic(KeyEvent.VK_N);
       displacement.setSelected(true);
        //Displacement Button, set to automatically be clicked

       JRadioButton accel = new JRadioButton("Acceleration");
       accel.setMnemonic(KeyEvent.VK_A);
       accel.setActionCommand("acceleration");
        //Acceleration Button

       JRadioButton time = new JRadioButton("Change in time");
       time.setMnemonic(KeyEvent.VK_S);
       time.setActionCommand("deltaT");
        //The change in time button

       // Creates the group of buttons
       ButtonGroup group = new ButtonGroup();
       group.add(displacement);
       group.add(accel);
       group.add(time);

              myListener = new RadioListener();
                displacement.addActionListener(myListener);
                accel.addActionListener(myListener);
                time.addActionListener(myListener);


      // Set up the picture label
       pic = new JLabel(new ImageIcon(""+"numbers" + ".jpg"));          //Set the Default Image

       pic.setPreferredSize(new Dimension(177, 122)); 


       // Puts the radio buttons down
       JPanel panel = new JPanel();
       panel.setLayout(new GridLayout(0, 1));
       panel.add(displacement);
       panel.add(accel);
       panel.add(time);


       setLayout(new BorderLayout());
       add(panel, BorderLayout.WEST);
       add(pic, BorderLayout.CENTER);
       setBorder(BorderFactory.createEmptyBorder(40,40,40,40));
   } 
  if ( displacement.setSelected(true))
  {

  }


   //Listening to the buttons
   class RadioListener implements ActionListener { 
       public void actionPerformed(ActionEvent e) {
           pic.setIcon(new ImageIcon(""+e.getActionCommand() 
                                         + ".jpg"));
       }
   }

   public static void main(String s[]) {
        frame = new JFrame("∆x = Vavg * time");
        frame.addWindowListener(new WindowAdapter() {

1 个答案:

答案 0 :(得分:2)

您将true设为isSelected()。但是,根据您的描述,您需要检查它是否已被选中。

使用:

if ( displacement.isSelected())
  {

  }

而不是:

if ( displacement.setSelected(true))
  {

  }