有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

swing Java:在字段中显示actionEvent

我需要在我在这个程序中创建的一个字段中显示文本,该字段在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);
    }
  }

共 (1) 个答案

  1. # 1 楼答案

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

    final JTextField field = new JTextField
    

    原因是您试图访问匿名类中的局部变量,它需要是declarefinal


    你应该注意的其他事项:

    • 在事件调度线程上运行Swing应用程序。详见Initial Threads

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