gpt4 book ai didi

java - 如何确保该按钮已被选中?

转载 作者:行者123 更新时间:2023-11-30 03:43:05 25 4
gpt4 key购买 nike

作业是一个基本的投票系统,在 3 个人之间进行选择,或者第四个按钮是“拒绝回答”

我不断收到“找不到符号”等错误

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 的一部分。

最佳答案

if(jRadioButton.isSelected())

这里的jRadioButton没有定义。

您想要获取触发事件的源(即一、二、三或四):

if(((JRadioButton)e.getSource()).isSelected())

这会获取触发事件的对象,将其转换为 JRadioButton,并检查是否选择了该单选按钮。

这至少应该消除“找不到符号”错误。

关于java - 如何确保该按钮已被选中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26384803/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com