Select all JCheckboxes when clicking button

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

  

"java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: java.awt.Component.setSelected"

I made an example of a graphical interface in netbeans.

Follow the code below:

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                   
}
    
asked by anonymous 29.05.2018 / 14:46

1 answer

1

There are two errors in the code:

1- The container of type Box does not return a JCheckBox , it returns the most generic type Component , which is the class from which all swing API components inherit. So you can not invoke the setSelected() method because the class you mentioned does not have this method, since it is inherited from components that are subtypes of AbstractButton ", and because the compiler does not assume that you actually want to only configure the components that are checkbox as selected, that code will not compile. You must first ensure that the component is an instance of JCheckBox .

2- Even correcting as mentioned above, to cast without error, method setSelected() " is given a Boolean type, which represents whether it will be marked (true) or not (false) and you are not passing anything.

Correct 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 documentation of the class / method before venturing with the component, because it shows what it is for, what parameters it receives and if it has a return. The two errors I mentioned could be avoided if the documentation of the respective methods had been consulted.

    
29.05.2018 / 15:01