[英]How do I make sure that the button is checked?
分配是在3個人之間進行選擇的基本投票系統,或者第4個按鈕是“拒絕回答”
我不斷收到諸如“找不到符號”之類的錯誤
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Vote
{
JLabel label;
public static void main (String[] args)
{
Vote sr = new Vote();
}
public Vote ()
{
JFrame frame = new JFrame("Please Choose your next President:");
JRadioButton one = new JRadioButton("Name 1");
JRadioButton two = new JRadioButton("Name 2");
JRadioButton three = new JRadioButton("Name 3");
JRadioButton four = new JRadioButton("I decline to answer");
JPanel panel = new JPanel();
panel.add(one);
panel.add(two);
panel.add(three);
panel.add(four);
ButtonGroup but = new ButtonGroup();
but.add(one);
but.add(two);
but.add(three);
but.add(four);
one.addActionListener(new MyAction());
two.addActionListener(new MyAction());
three.addActionListener(new MyAction());
four.addActionListener(new MyAction());
label = new JLabel("Please Select a Canidate for President ");
label.setHorizontalAlignment(JLabel.CENTER);
frame.add(panel, BorderLayout.NORTH);
frame.add(label, BorderLayout.CENTER);
frame.setSize(400, 100);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public class MyAction implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
if (jRadioButton.isSelected())
{
label.setText(e.getActionCommand());
JOptionPane.showMessageDialog(null, "You have selected " +
e.getActionCommand()
+ " as the new President. Thank you for voting.");
}
else
{
label.setText(e.getActionCommand());
JOptionPane.showMessageDialog(null, "You have selected " +
e.getActionCommand() + " Thank you for voting.");
}
}
}
}
因此,基本功能是從4個可用的單選按鈕中選擇一個名稱,並在選擇任何按鈕后出現一個新窗口,說謝謝您的投票。
我希望根據所按下的單選按鈕有不同的響應,因此,如果按下一個按鈕並說“我拒絕回答”,則將對此做出適當的響應。
請檢查我的If語句,因為我認為大多數錯誤的.isSelected
是.isSelected
的一部分。
if(jRadioButton.isSelected())
jRadioButton此處未定義。
您可能想要獲取觸發事件的源(即,一,二,三或四):
if(((JRadioButton)e.getSource()).isSelected())
這將獲取觸發事件的對象,將其強制轉換為JRadioButton,並檢查是否已選中該單選按鈕。
那至少應該擺脫您的“找不到符號”錯誤。
您沒有名為jRadioButton
對象。 嘗試改變
jRadioButton.isSelected()
至
((JRadioButton)e.getSource()).isSelected()
另外,如果要檢查是否選擇了第4個 JRadioButton
,則請執行以下操作:
four.setActionCommand("fourth");
然后在if
語句中
if ("fourth".equals(e.getActionCommand()) && ((JRadioButton)e.getSource()).isSelected())
它將檢查動作命令是否匹配了第四個單選按鈕,以及是否已選擇它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.