【问题标题】:ActionListener class doesn't get triggered for CheckBox不会为 CheckBox 触发 ActionListener 类
【发布时间】:2015-09-26 17:21:04
【问题描述】:

我正在为一个项目创建这个软件,我所做的是我创建了一个方法“沙拉”在这里发生的情况是用户可以选择最多 2 个沙拉。沙拉的名称来自数据库,我创建了复选框动态的。

这很好用,我可以获取值并将其插入数据库。所以我想要更新插入的行。我创建了一个方法来setselected() 用户之前选择的所有复选框。所以正如我上面所说的,我创建了这个方法来选择最多 2 个复选框。当我尝试插入时它工作正常。但是当我尝试更新 ActionListener 时不起作用。

我在 ActionListener 没有触发的构造函数中使用 setSelected(true)。我应该在Salad() 中做什么??

 public void Salad()
{

    int count =0 ;//to count rows in result set 
    String sql="Select name from foodmenue where type='Salad' and menue='"+selecmenue+"'  ";

    try {
        pst=con.prepareStatement(sql);
        rs=pst.executeQuery();
        while(rs.next())
        {
            count++;
        }
        if(count!=0)
        {
            rs=pst.executeQuery();
            JCheckBox [] a=new JCheckBox[count];
            jPanel7.setLayout(new GridLayout());
            int x=0;
             while(rs.next())
           {
             a[x]=new JCheckBox(rs.getString("name"));
             a[x].setName(rs.getString("name"));

              jPanel7.add(a[x]); 
             a[x].setVisible(true);
              a[x].addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {

            if( e.getSource() instanceof JCheckBox){

               String s=((JCheckBox) e.getSource()).getName();
                if(((JCheckBox) e.getSource()).isSelected())
                {
                    if(selsalad<2)//selsalad is 0 in the bigining
                    {
                        selectedsalad[selsalad]=((JCheckBox) e.getSource()).getName();
                        selsalad=selsalad+1;
                    }
                    else
                    {
                        ((JCheckBox) e.getSource()).setSelected(false);
                        showMessageDialog(null, "you cant have more than 2 salads");
                    }
                }
                if(!((JCheckBox) e.getSource()).isSelected())
                {  
                    if(selectedsalad[0].equals(s)||  selectedsalad[1].equals(s)   )
                    {
                        if(selsalad<2)
                        {
                        selectedsalad[selsalad]="";
                        }
                        selsalad=selsalad-1;
                        showMessageDialog(null, selsalad);
                    }     
                }               }    
        }
    });
                x++;
            }
        }  
    } catch (Exception e) {
        showMessageDialog(null, e);
    }
}  

这就是我填写复选框的方式

    for(Component c : jPanel7.getComponents())
   {
       if(c instanceof JCheckBox)
       {
           JCheckBox temp=(JCheckBox) c;
           if(temp.getName().equals(s1)){
               temp.setSelected(true);

           }
           if(temp.getName().equals(s2)){
               temp.setSelected(true);
           }
       }
   } 

MCVE提供更好的想法

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

import static javax.swing.JOptionPane.showMessageDialog;


public class NewJFrame extends javax.swing.JFrame {


    int selsalad=0;//count of the selected checkbox this cant go more than 2
    String selectedsalad[]=new String[2];
    // Variables declaration - do not modify
    private javax.swing.JPanel jPanel1;

    public NewJFrame() {
        initComponents();
        Salad();
        showMessageDialog(null, "uncomment promlemmethod to see the probelm after you try this one");
        problemmehtod();
    }

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 561, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGap(0, 470, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>

    public void problemmehtod(){ // this is the problem now i can select any much when i call this i commented this one

        for(Component c : jPanel1.getComponents())
        {
            if(c instanceof JCheckBox)
            {
                JCheckBox temp=(JCheckBox) c;
                if(temp.getName().equals("a1")){
                    temp.setSelected(true);

                }
                if(temp.getName().equals("a2")){
                    temp.setSelected(true);
                }
            }
        }

    }

    public void Salad()
    {
        JCheckBox a[]=new JCheckBox[5];
        // int count =0 ;//to count rows in result set


        try {

            for(int x=0;x<5;x++)
            {

                jPanel1.setLayout(new GridLayout());


                a[x]=new JCheckBox("a"+String.valueOf(x));
                a[x].setName("a"+String.valueOf(x));

                jPanel1.add(a[x]);
                a[x].setVisible(true);
                a[x].addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {

                        if( e.getSource() instanceof JCheckBox){

                            String s=((JCheckBox) e.getSource()).getName();
                            if(((JCheckBox) e.getSource()).isSelected())
                            {
                                if(selsalad<2)
                                {
                                    selectedsalad[selsalad]=((JCheckBox) e.getSource()).getName();
                                    selsalad=selsalad+1;
                                }
                                else
                                {
                                    ((JCheckBox) e.getSource()).setSelected(false);
                                    showMessageDialog(null, "you cant have more than 2 salads");
                                }
                            }
                            if(!((JCheckBox) e.getSource()).isSelected())
                            {
                                if(selectedsalad[0].equals(s)||  selectedsalad[1].equals(s)   )
                                {
                                    if(selsalad<2)
                                    {
                                        selectedsalad[selsalad]="";
                                    }
                                    selsalad=selsalad-1;
                                    //showMessageDialog(null, selsalad);
                                }
                            }
                        }
                    }
                });
            }
        } catch (Exception e) {
            showMessageDialog(null, e);
        }
    }
    // End of variables declaration
}

【问题讨论】:

    标签: java swing constructor actionlistener dynamic-programming


    【解决方案1】:

    选中的复选框数量在每个复选框的actionListener 上进行检查。当您在选择框上调用 setSelected(true) 时,不会调用动作侦听器。

    如果你想调用动作监听器,你需要调用doClick()

    JCheckBox temp=(JCheckBox) c;
    if(temp.getName().equals("a1")){
       temp.doClick();
    }
    if(temp.getName().equals("a2")){
       temp.doClick();
    }
    

    此外,由于两个 if 语句的作用相同,因此您可以将它们组合起来。

    if(temp.getName().equals("a1") || temp.getName().equals("a2")){
        temp.doClick();
    }
    

    【讨论】:

    • 这很有效,非常感谢您为我提供的帮助和时间
    【解决方案2】:

    您的问题是,当您以编程方式选择 JCheckBox 时,您没有更新 selsalad。也许更好的是完全摆脱 selsalad 变量,而是在 ActionListener 中遍历 ArrayList&lt;JCheckBox&gt; 并准确计算已选择的数量。或者将您的 JCheckBox 数组设为一个字段,改进其名称并对其进行迭代。

    例如:

    import java.awt.Component;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class NewPanel extends JPanel {
        private static final int CHECK_BOX_COUNT = 5;
        public static final int MAX_SELECTED = 2;
        private List<JCheckBox> checkBoxes = new ArrayList<>();
    
        public NewPanel() {
            setLayout(new GridLayout(0, 1));
            ActionListener actionListener = new CheckBoxListener();
            for (int i = 0; i < CHECK_BOX_COUNT; i++) {
                String name = "a" + i;
                JCheckBox checkBox = new JCheckBox(name);
                checkBox.setActionCommand(name);
                checkBox.addActionListener(actionListener);
                add(checkBox); // add to gui
                checkBoxes.add(checkBox); // add to ArrayList
            }
    
            checkBoxes.get(1).setSelected(true);
            checkBoxes.get(2).setSelected(true);
        }
    
        private class CheckBoxListener implements ActionListener {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedCount = 0;
                for (JCheckBox jCheckBox : checkBoxes) {
                    if (jCheckBox.isSelected()) {
                        selectedCount++;
                    }
                }
                if (selectedCount > MAX_SELECTED) {
                    Component parent = NewPanel.this;
                    String msg = String.format("You've selected too many checkboxes as only %d can be selected", 
                            MAX_SELECTED);
                    String title = "Too Many CheckBoxes Selected";
                    int type = JOptionPane.ERROR_MESSAGE;                        
                    JOptionPane.showMessageDialog(parent, msg, title, type);
    
                    ((JCheckBox) e.getSource()).setSelected(false);
                }
            }
        }
    
        public List<String> getSelectedActionCommands() {
            List<String> resultList = new ArrayList<>();
            for (JCheckBox checkBox : checkBoxes) {
                if (checkBox.isSelected()) {
                    resultList.add(checkBox.getActionCommand());
                }
            }
            return resultList;
        }
    
        private static void createAndShowGui() {
            NewPanel mainPanel = new NewPanel();
    
            int result = JOptionPane.showConfirmDialog(null, mainPanel, 
                    "Select Options", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
            if (result == JOptionPane.OK_OPTION) {
                System.out.println("Selected Options: " + mainPanel.getSelectedActionCommands());
            }
    
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGui();
                }
            });
        }
    
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多