2014-12-22 111 views
1

我試圖讓它取決於是否按下一個單選按鈕,它將使用Java圖形並創建一個帶有預設圖形的小程序。儘管我試圖使用if語句,但它告訴我我無法將JRadioButton轉換爲布爾值,但我覺得這不會是正確的方法。我拉我的頭髮,因爲我不明白如何做到這一點。將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() { 
+0

我仍然需要做的一類,其中小程序將運行,但我需要得到它改變它是否被按下 – HLatfullin

回答

2

要設置true到​​。不過,根據你的描述,你想檢查它是否被選中。

用途:

if (displacement.isSelected()) 
    { 

    } 

相反的:

if (displacement.setSelected(true)) 
    { 

    } 
+0

好的,我會嘗試一下,非常感謝:D – HLatfullin

+0

快速提問:當我這樣做時,我在不同的課上做,它說可變位移無法解決。我擴展了其他課程,但那不起作用,所以我如何得到它,以便它可以達到可變位移。 – HLatfullin

+0

我真的不知道該怎麼做,所以如果有人能幫助我,這將是太棒了! – HLatfullin