Java初学者GUI单选按钮

时间:2013-08-26 22:20:04

标签: java swing class jradiobutton itemlistener

我一直在努力学习Java,我在使用这个程序时遇到了麻烦。假设只是两个单选按钮(男/女)然后显示一个消息对话框,你选择了哪个,但我一直收到错误。这是我的代码:

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

public class gui2 extends JFrame {
   private JRadioButton male;
   private JRadioButton female;
   private ButtonGroup group;

   public gui2() {
      super("the Title");
      setLayout ( new FlowLayout());

      male = new JRadioButton("male", true);
      female = new JRadioButton("female", false);

      add(male);
      add(female);

      group = new ButtonGroup();
      group.add(male);
      group.add(female);

      HandlerClass handler = new HandlerClass();
      male.addItemListener(handler);
      female.addItemListener(handler);
   }
   private HandlerClass implements ItemListener {
      public void itemStateChanged(ItemEvent event) {
         JOptionPane.showMessageDialog(null, String.format("%s", ItemEvent.SELECTED));   
      }
   }
}

对于那些认识苹果课程的人,你会知道我在哪里学习

import javax.swing.JFrame;

class apples {
   public static void main(String args[]) {

      gui2 go = new gui2();
      go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      go.setSize(300,200);
      go.setVisible(true);
   }
}

以下是我遇到的错误:

gui2.java:28: error: <identifier> expected
   private HandlerClass implements ItemListener {
                       ^
gui2.java:28: error: <identifier> expected
   private HandlerClass implements ItemListener {
                                               ^
gui2.java:33: error: class, interface, or enum expected
}
^
3 errors

1 个答案:

答案 0 :(得分:4)

嗯,首先:源代码在这里无关紧要。所有你需要做的就是

private class HandlerClass implements ItemListener

而不是

private HandlerClass implements ItemListener