gpt4 book ai didi

Java:在字段中显示actionEvent

转载 作者:行者123 更新时间:2023-12-01 12:41:45 25 4
gpt4 key购买 nike

我需要在我在此程序中创建的字段中显示文本,该字段在 actionEvent 中标识,即 RadioButton 选择。我很难让选择显示在字段中。请帮忙?

  import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class JBasketball {

public static void main(String args[]) {

JFrame frame = new JFrame("JBasketball");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JTextField field = new JTextField(16);

JPanel panel = new JPanel(new FlowLayout());

ButtonGroup group = new ButtonGroup();
JRadioButton sixers = new JRadioButton("Philadelphia 76ers");
JRadioButton raptors = new JRadioButton("Toronto Raptors");
JRadioButton lakers = new JRadioButton("Los Angeles Lakers");
JRadioButton sonics = new JRadioButton("Seattle Supersonics");
JRadioButton bullets = new JRadioButton("Baltimore Bullets");

ActionListener action = new ActionListener() {

public void actionPerformed(ActionEvent actionEvent) {
JRadioButton aButton = (JRadioButton) actionEvent.getSource();

String team = aButton.getText();
//This is where I need the field to display the team name
field.setText(team);
}
};

panel.add(sixers);
group.add(sixers);
panel.add(raptors);
group.add(raptors);
panel.add(lakers);
group.add(lakers);
panel.add(sonics);
group.add(sonics);
panel.add(bullets);
group.add(bullets);
panel.add(field);


sixers.addActionListener(action);
raptors.addActionListener(action);
lakers.addActionListener(action);
sonics.addActionListener(action);
bullets.addActionListener(action);
field.addActionListener(action);

frame.add(panel);
frame.setSize(500, 130);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
}
}

最佳答案

一旦编译完成,它就可以正常工作。您只需声明文本字段final

final JTextField field = new JTextField

原因是您正在尝试访问匿名类中的局部变量,并且需要将其声明为final

<小时/>

其他需要注意的事项:

  • 在事件调度线程上运行 Swing 应用程序。查看更多Initial Threads

  • 我不会像您一样在 main 中完成所有工作。为类创建一个构造函数并在那里完成工作,或者创建一些 init 方法。并在 main 中实例化构造函数或调用 init 方法,这最适合您。

关于Java:在字段中显示actionEvent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25041263/

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