gpt4 book ai didi

java - JRadioButton 转换为 boolean 值?

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

我正在尝试根据是否按下单选按钮来使用 Java 图形并创建一个带有预设绘图的小程序。虽然我尝试使用 if 语句,但它告诉我无法将 JRadioButton 转换为 boolean 值,但我觉得这不是解决此问题的正确方法。我拉扯我的头发,因为我不明白该怎么做。

非常感谢帮助/指导: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() {

最佳答案

您正在将 true 设置为 isSelected()。但是,根据您的描述,您想要检查它是否已被选中。

用途:

if ( displacement.isSelected())
{

}

而不是:

if ( displacement.setSelected(true))
{

}

关于java - JRadioButton 转换为 boolean 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27608025/

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