如何在单击按钮时禁用面板的组件

时间:2016-09-13 10:07:35

标签: java arrays swing jbutton point

我的代码有些问题!....我能够在JPanel中以圆形形式创建一个包含下面代码的12个JButton数组!...我在每个JButton上设置一个actionListener,并且我想在点击其中一个Jbuttons后禁用其他....然后启用它.....为了更多的理解,这是我的代码

int n = 10;


public Beginner() {

          int radius = 200;
          Point center = new Point (250, 250);

          double angle = Math.toRadians(360 / n);

          List <Point> points = new ArrayList<Point> ();

          points.add(center);

          for (int i = 0; i < n; i++) {
              double theta = i * angle;

              int dx = (int) (radius * Math.sin(theta));

              int dy = (int) (radius * Math.cos(theta));

              Point p = new Point (center.x + dx , center.y + dy);

              points.add(p);
          }

          draw (points);

          }
           public void draw (List<Point> points) {

               JPanel panels = new JPanel();

               SpringLayout spring = new SpringLayout();

               int count = 1;
               for (Point point: points) {

                   quest = new JButton("Question " + count);
                   quest.setForeground(Color.BLACK);
                    Font fonte = new Font("Script MT Bold", Font.PLAIN, 20);
                    quest.setFont(fonte);

                   add (quest);
                   count++;

                   spring.putConstraint(SpringLayout.WEST, quest, point.x, SpringLayout.WEST, panels );

                   spring.putConstraint(SpringLayout.NORTH, quest, point.y, SpringLayout.NORTH, panels );

                   setLayout(spring);

                   panels.setOpaque(false);
                   panels.setVisible(true);
                   panels.setLocation(5,5);

                   add(panels);
        quest.addActionListener(new ActionListener(){
                 public void actionPerformed (ActionEvent q) {
                if (point.equals(points.get(0))) {

              //Some action....
              //It is at this point that every other Jbutton in the panel is to be disabled until the action ends..... It is here that I need help!!!

1 个答案:

答案 0 :(得分:2)

试试这个解决方案:

            quest.addActionListener(new java.awt.event.ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    JButton b = (JButton)e.getSource();
                    for(Component c : yourPanel.getComponents()){
                        if(c instanceof JButton && !c.equals(b)){
                            c.setEnabled(false);
                        }
                    }
                }
            });