【问题标题】:Method to pass argument to select Yes and No radio button将参数传递给选择是和否单选按钮的方法
【发布时间】:2022-01-12 05:55:45
【问题描述】:

我正在尝试传递方法参数来选择“是”单选按钮或“否”单选按钮。

我的代码

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Set;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

public class Demo {
  public static void main(String[] args) {
      new Demo();
  }
  public Demo() {
      EventQueue.invokeLater(new Runnable() {
          @Override
          public void run() {
              JFrame frame = new JFrame();
              frame.add(new TestPane());
              frame.pack();
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
          }
      });
  }
  public class TestPane extends JPanel {
    private static final int NUMBER_CHECK_BOX = 10;
    JCheckBox[] checkBoxList = new JCheckBox[NUMBER_CHECK_BOX];
    JRadioButton yes = new JRadioButton("yes");
    JRadioButton no = new JRadioButton("No");
      private Set<String> selectedValues = new HashSet<>(8);
   //   JPanel panelCheckBox = new JPanel(new WrapLayout(WrapLayout.LEADING));
      public TestPane() {
          setBorder(new EmptyBorder(20, 20, 20, 20));
          setLayout(new GridBagLayout());
          JTextField textField = new JTextField(40);
          JPanel panelCheckBox = new JPanel(new WrapLayout(WrapLayout.LEADING));
          yes.setSelected(true);
          yes.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  if (yes.isSelected()) {
                      textField.setEnabled(true);
                      toggleCheckBoxesEnabled(false);
                      //panelCheckBox.setEnabled(false);
                  }
              }
          });
          no.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  if (no.isSelected()) {
                    textField.setText("");
                      textField.setEnabled(false);
                      toggleCheckBoxesEnabled(true);
                  }
              }
          });
          ButtonGroup bg = new ButtonGroup();
          bg.add(yes);
          bg.add(no);
          JPanel enterClassPane = new JPanel(new GridBagLayout());
          enterClassPane.setBorder(new TitledBorder(null, "Enetr Your MetaClass", TitledBorder.LEADING, TitledBorder.TOP, null, null));
          enterClassPane.add(yes);
          enterClassPane.add(no);
          for (int i = 0; i < NUMBER_CHECK_BOX; i++) {
              checkBoxList[i] = new JCheckBox("Diagram " + i);
              checkBoxList[i].setEnabled(false);
              panelCheckBox.add(checkBoxList[i]);
              checkBoxList[i].addActionListener(new ActionListener() {
                  @Override
                  public void actionPerformed(ActionEvent e) {
                      System.out.println("Selected Diagram " + e.getActionCommand());
                      if (e.getSource() instanceof JCheckBox) {
                          JCheckBox cb = (JCheckBox) e.getSource();
                          if (cb.isSelected()) {
                              selectedValues.add(cb.getActionCommand());
                          } else {
                              selectedValues.remove(cb.getActionCommand());
                          }
                      }
                  }
              });
          }
          JPanel classPane = new JPanel(new GridBagLayout());
          classPane.setBorder(new TitledBorder(null, "Enter Meta Class", TitledBorder.LEADING, TitledBorder.TOP, null, null));
          classPane.add(textField);
          JPanel actionsPane = new JPanel(new GridBagLayout());
          JButton btnCancel = new JButton("Cancel");
          btnCancel.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  System.exit(1);
              }
          });
          JButton btnOkay = new JButton("Okay");
          btnOkay.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  //Text field
                  System.out.println(textField.getText());

                  for (String command : selectedValues) {
                      System.out.println(command);
                  }
              }
          });
          actionsPane.add(btnOkay);
          actionsPane.add(btnCancel);

          GridBagConstraints gbc = new GridBagConstraints();
          gbc.insets = new Insets(4, 4, 4, 4);
          gbc.gridwidth = gbc.REMAINDER;
          gbc.fill = gbc.HORIZONTAL;

          add(enterClassPane, gbc);
          add(new JScrollPane(panelCheckBox), gbc);
          add(classPane, gbc);
          add(actionsPane, gbc);
      }
        
      private void toggleCheckBoxesEnabled(boolean enabled) {
        for (JCheckBox box : checkBoxList) {
            box.setEnabled(enabled);
        }
    }
  }
  public void methodName(String parameterName){ 
    if (parameterName.equals("yes")) {
        buttonyes.setSelected(true);
    } 
    else if(parameterName.equals("no")){ 
        buttonNo.setSelected(true);
    }
    else{
        buttonYes.setSelected(false);
        buttonNo.setSelected(false);
    }
}
  public class WrapLayout extends FlowLayout {
      private Dimension preferredLayoutSize;
     public WrapLayout() {
          super();
      }
      public WrapLayout(int align) {
          super(align);
      }
      public WrapLayout(int align, int hgap, int vgap) {
          super(align, hgap, vgap);
      }
      @Override
      public Dimension preferredLayoutSize(Container target) {
          return layoutSize(target, true);
      }
      @Override
      public Dimension minimumLayoutSize(Container target) {
          Dimension minimum = layoutSize(target, false);
          minimum.width -= (getHgap() + 1);
          return minimum;
      }
      private Dimension layoutSize(Container target, boolean preferred) {
          synchronized (target.getTreeLock()) {
              int targetWidth = target.getSize().width;
              Container container = target;
              while (container.getSize().width == 0 && container.getParent() != null) {
                  container = container.getParent();
              }
              targetWidth = container.getSize().width;

              if (targetWidth == 0) {
                  targetWidth = Integer.MAX_VALUE;
              }
              int hgap = getHgap();
              int vgap = getVgap();
              Insets insets = target.getInsets();
              int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2);
              int maxWidth = targetWidth - horizontalInsetsAndGap;
              //  Fit components into the allowed width
              Dimension dim = new Dimension(0, 0);
              int rowWidth = 0;
              int rowHeight = 0;
              int nmembers = target.getComponentCount();
              for (int i = 0; i < nmembers; i++) {
                  Component m = target.getComponent(i);
                  if (m.isVisible()) {
                      Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();
                      //  Can't add the component to current row. Start a new row.
                      if (rowWidth + d.width > maxWidth) {
                          addRow(dim, rowWidth, rowHeight);
                          rowWidth = 0;
                          rowHeight = 0;
                      }
                      //  Add a horizontal gap for all components after the first
                      if (rowWidth != 0) {
                          rowWidth += hgap;
                      }

                      rowWidth += d.width;
                      rowHeight = Math.max(rowHeight, d.height);
                  }
              }

              addRow(dim, rowWidth, rowHeight);

              dim.width += horizontalInsetsAndGap;
              dim.height += insets.top + insets.bottom + vgap * 2;

              Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target);

              if (scrollPane != null && target.isValid()) {
                  dim.width -= (hgap + 1);
              }

              return dim;
          }
      }

      private void addRow(Dimension dim, int rowWidth, int rowHeight) {
          dim.width = Math.max(dim.width, rowWidth);

          if (dim.height > 0) {
              dim.height += getVgap();
          }

          dim.height += rowHeight;
      }
  }
}

在默认情况下是单选按钮被选中。

我想用“是”或“否”在方法中传递参数,

  • 如果我在方法中传递“是”,则应该选择“是”单选按钮并运行。

  • 如果我通过“否”单选按钮,则不应选择并执行单选按钮。

【问题讨论】:

  • 你遇到了什么问题?

标签: java swing methods jframe awt


【解决方案1】:

如果您想创建一个方法或想将其添加到您的方法之一,您应该提供一个字符串参数,您可以设置“是或否”。然后您可以将以下代码添加到您的方法中。

public void methodName(String parameterName){ 

    if (parameterName.equals("Yes")) {
        buttonYes.setSelected(true);
    } 
    else if(parameterName.equals("No")){ 
        buttonNo.setSelected(true);
    }
    else{
        buttonYes.setSelected(false);
        buttonNo.setSelected(false);
    }
}

确保您有权访问该对象。您在构造函数中创建了单选按钮,因此在垃圾收集器执行方法后它会丢失。 parameterName 代表您的参数字符串。 buttonYes 和 buttonNo 是 Yes 和 No Radio-Button 的名称。 else 是错误的参数。您可以根据需要更改默认情况。在这种情况下,如果您提示“可能”这样的错误答案,则不会选择单选按钮。我强烈建议将单选按钮和按钮组声明为构造函数之外的属性

短解:

 import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Set;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.border.TitledBorder;

public class Demo {
public static void main(String[] args) {
   new Demo();
}
public Demo() {
   EventQueue.invokeLater(new Runnable() {
       @Override
       public void run() {
           JFrame frame = new JFrame();
           frame.add(new TestPane());
           frame.pack();
           frame.setLocationRelativeTo(null);
           frame.setVisible(true);
       }
   });
}
public class TestPane extends JPanel {
 private static final int NUMBER_CHECK_BOX = 10;
 JCheckBox[] checkBoxList = new JCheckBox[NUMBER_CHECK_BOX];
 JRadioButton yes = new JRadioButton("yes");
 JRadioButton no = new JRadioButton("No");
 ButtonGroup bg = new ButtonGroup();
   private Set<String> selectedValues = new HashSet<>(8);
//   JPanel panelCheckBox = new JPanel(new WrapLayout(WrapLayout.LEADING));

   //You can change Method Name and Parameter Name
   public void methodName(String parameterName){ 

       if (parameterName.equals("Yes")) {
           yes.setSelected(true);
       } 
       else if(parameterName.equals("No")){ 
           no.setSelected(true);
       }
       else{
           yes.setSelected(false);
           no.setSelected(false);
       }
   }

   public TestPane() {
       setBorder(new EmptyBorder(20, 20, 20, 20));
       setLayout(new GridBagLayout());
       JTextField textField = new JTextField(40);
       JPanel panelCheckBox = new JPanel(new WrapLayout(WrapLayout.LEADING));
       yes.setSelected(true);
       yes.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               if (yes.isSelected()) {
                   textField.setEnabled(true);
                   toggleCheckBoxesEnabled(false);
                   //panelCheckBox.setEnabled(false);
               }
           }
       });
       no.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               if (no.isSelected()) {
                 textField.setText("");
                   textField.setEnabled(false);
                   toggleCheckBoxesEnabled(true);
               }
           }
       });
       bg.add(yes);
       bg.add(no);
       JPanel enterClassPane = new JPanel(new GridBagLayout());
       enterClassPane.setBorder(new TitledBorder(null, "Enetr Your MetaClass", TitledBorder.LEADING, TitledBorder.TOP, null, null));
       enterClassPane.add(yes);
       enterClassPane.add(no);
       for (int i = 0; i < NUMBER_CHECK_BOX; i++) {
           checkBoxList[i] = new JCheckBox("Diagram " + i);
           checkBoxList[i].setEnabled(false);
           panelCheckBox.add(checkBoxList[i]);
           checkBoxList[i].addActionListener(new ActionListener() {
               @Override
               public void actionPerformed(ActionEvent e) {
                   System.out.println("Selected Diagram " + e.getActionCommand());
                   if (e.getSource() instanceof JCheckBox) {
                       JCheckBox cb = (JCheckBox) e.getSource();
                       if (cb.isSelected()) {
                           selectedValues.add(cb.getActionCommand());
                       } else {
                           selectedValues.remove(cb.getActionCommand());
                       }
                   }
               }
           });
       }
       JPanel classPane = new JPanel(new GridBagLayout());
       classPane.setBorder(new TitledBorder(null, "Enter Meta Class", TitledBorder.LEADING, TitledBorder.TOP, null, null));
       classPane.add(textField);
       JPanel actionsPane = new JPanel(new GridBagLayout());
       JButton btnCancel = new JButton("Cancel");
       btnCancel.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               System.exit(1);
           }
       });
       JButton btnOkay = new JButton("Okay");
       btnOkay.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) {
               //Text field
               System.out.println(textField.getText());

               for (String command : selectedValues) {
                   System.out.println(command);
               }
           }
       });
       actionsPane.add(btnOkay);
       actionsPane.add(btnCancel);

       GridBagConstraints gbc = new GridBagConstraints();
       gbc.insets = new Insets(4, 4, 4, 4);
       gbc.gridwidth = gbc.REMAINDER;
       gbc.fill = gbc.HORIZONTAL;

       add(enterClassPane, gbc);
       add(new JScrollPane(panelCheckBox), gbc);
       add(classPane, gbc);
       add(actionsPane, gbc);
   }
     
   private void toggleCheckBoxesEnabled(boolean enabled) {
     for (JCheckBox box : checkBoxList) {
         box.setEnabled(enabled);
     }
 }
}
public void methodName(String parameterName){ 
 if (parameterName.equals("yes")) {
     buttonyes.setSelected(true);
 } 
 else if(parameterName.equals("no")){ 
     buttonNo.setSelected(true);
 }
 else{
     buttonYes.setSelected(false);
     buttonNo.setSelected(false);
 }
}
public class WrapLayout extends FlowLayout {
   private Dimension preferredLayoutSize;
  public WrapLayout() {
       super();
   }
   public WrapLayout(int align) {
       super(align);
   }
   public WrapLayout(int align, int hgap, int vgap) {
       super(align, hgap, vgap);
   }
   @Override
   public Dimension preferredLayoutSize(Container target) {
       return layoutSize(target, true);
   }
   @Override
   public Dimension minimumLayoutSize(Container target) {
       Dimension minimum = layoutSize(target, false);
       minimum.width -= (getHgap() + 1);
       return minimum;
   }
   private Dimension layoutSize(Container target, boolean preferred) {
       synchronized (target.getTreeLock()) {
           int targetWidth = target.getSize().width;
           Container container = target;
           while (container.getSize().width == 0 && container.getParent() != null) {
               container = container.getParent();
           }
           targetWidth = container.getSize().width;

           if (targetWidth == 0) {
               targetWidth = Integer.MAX_VALUE;
           }
           int hgap = getHgap();
           int vgap = getVgap();
           Insets insets = target.getInsets();
           int horizontalInsetsAndGap = insets.left + insets.right + (hgap * 2);
           int maxWidth = targetWidth - horizontalInsetsAndGap;
           //  Fit components into the allowed width
           Dimension dim = new Dimension(0, 0);
           int rowWidth = 0;
           int rowHeight = 0;
           int nmembers = target.getComponentCount();
           for (int i = 0; i < nmembers; i++) {
               Component m = target.getComponent(i);
               if (m.isVisible()) {
                   Dimension d = preferred ? m.getPreferredSize() : m.getMinimumSize();
                   //  Can't add the component to current row. Start a new row.
                   if (rowWidth + d.width > maxWidth) {
                       addRow(dim, rowWidth, rowHeight);
                       rowWidth = 0;
                       rowHeight = 0;
                   }
                   //  Add a horizontal gap for all components after the first
                   if (rowWidth != 0) {
                       rowWidth += hgap;
                   }

                   rowWidth += d.width;
                   rowHeight = Math.max(rowHeight, d.height);
               }
           }

           addRow(dim, rowWidth, rowHeight);

           dim.width += horizontalInsetsAndGap;
           dim.height += insets.top + insets.bottom + vgap * 2;

           Container scrollPane = SwingUtilities.getAncestorOfClass(JScrollPane.class, target);

           if (scrollPane != null && target.isValid()) {
               dim.width -= (hgap + 1);
           }

           return dim;
       }
   }

   private void addRow(Dimension dim, int rowWidth, int rowHeight) {
       dim.width = Math.max(dim.width, rowWidth);

       if (dim.height > 0) {
           dim.height += getVgap();
       }

【讨论】:

  • 感谢您的回答,我尝试了代码,但我不知道在哪里添加。请你帮我解决这个问题。
  • 如果你真的想这样做,你应该像String parameterName这样在构造函数中输入参数。然后,您可以在将 Radio-Buttons 放入 Button-Group 后添加代码。所以在这段代码之后:ButtonGroup bg = new ButtonGroup(); bg.add(yes); bg.add(no);
  • 对不起,我在按钮组下方添加了代码,但我不知道在哪里添加参数名称,我希望这是一个单独的方法。在那个方法中,我想传递这个参数。如果我通过“是”是单选按钮想要选择,如果我通过“否”,则没有单选按钮想要选择
  • 我刚刚编辑了我的答案。该方法仅在您有权访问对象时才有效。因此,您需要将它们作为属性。因此,您需要在 JCheckBox[] checkBoxList = new JCheckBox[NUMBER_CHECK_BOX]; 下的构造函数之外声明 JRadioButton yes = new JRadioButton("yes"); 之类的所有内容@
  • 你好 Mr. Gotta Gaming,我编辑了我的代码,你可以看到有问题,但我仍然不知道在哪里应用这个,你能帮我吗?这对我来说太棒了。
猜你喜欢
  • 2011-03-13
  • 2011-04-22
  • 2011-08-11
  • 2023-03-23
  • 1970-01-01
  • 2012-08-31
  • 1970-01-01
相关资源
最近更新 更多