[英]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.