我需要在我在此程序中创建的字段中显示文本,该字段在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);
}
}
答案 0 :(得分:1)
一旦你编译它就可以了。您只需要声明文本字段final
final JTextField field = new JTextField
原因是您正在尝试访问匿名类中的局部变量,并且需要声明final
。
您应该注意的其他事项:
在Event Dispatch Thread上运行Swing应用程序。详情请见Initial Threads
我不会像你一样在main
完成所有工作。为类创建一个构造函数并在那里完成工作,或者使用一些init方法。并在main中实例化构造函数或调用init方法,它最适合你。