我想製作一個代碼,當他用戶按下時它會打印出正確的,而不是打印出正確的它只是沒有做任何事情。我已經很清楚地研究這個話題,但我似乎無法找到正確的答案,如果任何機構可以幫助我將不勝感激當一個JRadioButton被點擊時,它將不會打印出正確的
import java.awt.FlowLayout;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
import javax.swing.JOptionPane;
public class JRadioButtonTest
{
public static void main(String[] args)
{
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JRadioButton Test");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JRadioButton button1 = new JRadioButton("0.4");
JRadioButton button2 = new JRadioButton("12");
JRadioButton button3 = new JRadioButton("37");
ButtonGroup colorButtonGroup = new ButtonGroup();
colorButtonGroup.add(button1);
colorButtonGroup.add(button2);
colorButtonGroup.add(button3);
frame.add(new JLabel("what is the density of a piece of rock that is 40 grams and 25cm3"));
frame.add(button1);
frame.add(button2);
frame.add(button3);
frame.pack();
frame.setVisible(true);
if(button2.isSelected()){
JOptionPane.showMessageDialog(null,"correct");
}
}
}
您需要將偵聽器添加到按鈕。使用您當前的代碼,只要框架顯示就會檢查按鈕。 –