我正在尝试制作它,以便根据是否按下单选按钮来使用Java图形并创建一个带有预设图形的小程序。尽管我尝试使用if语句,但是它告诉我不能将JRadioButton转换为boolean,但是我觉得这样做不是正确的方法。我拉头发是因为我不知道该怎么做。

帮助/指导将不胜感激: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() {

最佳答案

您正在将true设置为isSelected()。但是,根据您的描述,您要检查是否已选择它。

采用:

if ( displacement.isSelected())
  {

  }


代替:

if ( displacement.setSelected(true))
  {

  }

10-05 23:25