Select all Jcheckboxes by clicking button

Asked

Viewed 249 times

0

My application has a list of JCheckBox within a Box. I want to make a button to mark all of them, but my code is giving the following error when I click the button

"java.lang.Runtimeexception: Uncompilable source code - Erroneous Sym type: java.awt.Component.setSelected"

I did an example of a graphical user interface in netbeans.

Follows code:

package NewClass;

import javax.swing.Box;
import javax.swing.JCheckBox;
import javax.swing.JScrollPane;

public class NewJFrame extends javax.swing.JFrame {

    Box box = Box.createVerticalBox();
    public NewJFrame() {
        initComponents();
        for(int i=0 ; i<13 ; i++){
            box.add( new JCheckBox(Integer.toString(i)));
            box.getComponent(i).setName(Integer.toString(i));
        }
        Box box2 = Box.createHorizontalBox();
        box2.setBounds(10,10,60,200);
        box2.add(new JScrollPane(box));
        // Adciona Box Externo na janela
        this.add(box2);
    }

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

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("marcar tudo");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(129, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton1)
                .addContainerGap(181, Short.MAX_VALUE))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        for(int i=0 ; i<box.getComponentCount() ; i++){
           box.getComponent(i).setSelected(true);
        }
    }                                        

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        //</editor-fold>
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new NewJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   
}

1 answer

1


There are two errors in the code:

1- The container of the type Box does not return a JCheckBox, it returns the most generic type Component, which is the class from which all components of the swing API inherit. Therefore, you cannot invoke the method setSelected() because the class mentioned does not even have this method, since it is inherited from components that are subtypes of AbstractButton, And since the compiler doesn’t guess that you actually want to configure only the components that are checkbox as selected, this code won’t even compile. You first need to ensure that the component is an instance of JCheckBox.

2- even correcting as mentioned above, to cast without errors, the method setSelected() receives a boolean type, which represents whether it will be marked(true) or not(false) and you are not passing anything.

Fix the loop as below:

for(int i=0 ; i<box.getComponentCount() ; i++){
    if(box.getComponent(i) instanceof JCheckBox)
   ((JCheckBox)box.getComponent(i)).setSelected(true);
}

I recommend that you check the class/method documentation before venturing into the component, as it shows what it is for, what parameters it receives and if it has returns. The two errors I mentioned could be avoided if the documentation of the respective methods had been consulted.

  • The first mistake I didn’t really know, but I had really forgotten to put the "true", but I edited the question and put, so I knew the setSelected() method. Thank you for your reply.

  • @Pedroafonso but the recommendation remains valid, it is always good to consult the documentation, you end up learning more about the class and how it works. Most problems usually have the answer there, quick and easy. ;)

  • Yes, thank you :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.