Frage

I need to display text within a field I created in this program that is identified in the actionEvent, which is the RadioButton selection. I'm having a hard time getting the selection to display in the field. Please help?

  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);
    }
  }
War es hilfreich?

Lösung

It works fine, once you get it to compile. You just need to declare the text field final

final JTextField field = new JTextField

The reason is that you are trying to access a local variable inside an anonymous class, and it needs to be declare final.


Other things you should note:

  • Run your Swing apps on the Event Dispatch Thread. See more at Initial Threads

  • I wouldn't do all the work in the main as you are. Create a constructor for the class and do the work there, or some init method. And with instantiate the constructor in the main or call the init method, which ever bests suits you.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top