1

I am having troubles with the specifics of declaring an ActionListener and creating a new ActionEvent. My goal is to create a java.swing.Timer to run some code to proceed through slides, I am only struggling to declare the timer properly with an action in association with it.

public abstract class Actions implements ActionListener{
            public ActionListener TimePANG = new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent evt){

                            waitTime = Integer.valueOf(lblWaitput.getText());

                            if (waitTime <= 0){
                                waitTime = 60;
                            }

                            // METHOD TO CLEAR UP DEBRIS AND TO SPLIT INTO ARRAY
                            temp = txtList.getText();
                            temp = temp.toLowerCase();
                            selects = temp.split(" ");
                            for (i = 0; i < selects.length; i++){ //CLEANS UP VARIABLES FOR A PROPER PATH TO GRAB IMAGES FROM
                                selects[i] = "/SlideShow/" + selects[i] + ".jpg";
                                selectcount++;
                            }     // END OF CLEANING

                            //START OF SLIDE SHOW
                            for (x = 0; x <= selectcount; x++){//THE LOOP THAT CYCLES THROUGH THE IMAGES
                                lblDisplay.setIcon(null);
                                System.out.println(selects[x]); //THE VARIABLE WHICH THE IMAGE IS IN
                                lblDisplay.setIcon(new javax.swing.ImageIcon(getClass().getResource(selects[x]))); //DISPLAYING IMAGE
                            }
                }
            };
        } 

My Full Code is found below.

/*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    package SlideShow;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.Timer;
    /**
     *
     * @author palaceag196
     */
    public class MainSlides extends javax.swing.JFrame{

        String[] options = {"Soccer","Basketball","Football","Hockey","Ravioli","Banana","Pizza","Hotdog","Cat","Dog","Bird","Hamster"};
        String temp;
        String[] selects;
        int selectcount;
        int i, x;
        int waitTime;
        //              new ImageIcon(getClass().getResource(temp))
        /**
         * Creates new form MainSlides
         */

        public MainSlides() {
            initComponents();
        }
        public abstract class Actions implements ActionListener{
            public ActionListener TimePANG = new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent evt){

                            waitTime = Integer.valueOf(lblWaitput.getText());

                            if (waitTime <= 0){
                                waitTime = 60;
                            }

                            // METHOD TO CLEAR UP DEBRIS AND TO SPLIT INTO ARRAY
                            temp = txtList.getText();
                            temp = temp.toLowerCase();
                            selects = temp.split(" ");
                            for (i = 0; i < selects.length; i++){ //CLEANS UP VARIABLES FOR A PROPER PATH TO GRAB IMAGES FROM
                                selects[i] = "/SlideShow/" + selects[i] + ".jpg";
                                selectcount++;
                            }     // END OF CLEANING

                            //START OF SLIDE SHOW
                            for (x = 0; x <= selectcount; x++){//THE LOOP THAT CYCLES THROUGH THE IMAGES
                                lblDisplay.setIcon(null);
                                System.out.println(selects[x]); //THE VARIABLE WHICH THE IMAGE IS IN
                                lblDisplay.setIcon(new javax.swing.ImageIcon(getClass().getResource(selects[x]))); //DISPLAYING IMAGE
                            }
                }
            };
        }          
        /**
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {

            jScrollPane1 = new javax.swing.JScrollPane();
            listSelect = new javax.swing.JList();
            jScrollPane2 = new javax.swing.JScrollPane();
            txtList = new javax.swing.JTextArea();
            lblWaitput = new javax.swing.JTextField();
            jLabel1 = new javax.swing.JLabel();
            btnStart = new javax.swing.JButton();
            lblDisplay = new javax.swing.JLabel();

            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

            listSelect.setModel(new javax.swing.AbstractListModel() {
                String[] strings = { "Soccer", "Basketball", "Football", "Hockey", "Ravioli", "Banana", "Pizza", "Hotdog", "Cat", "Dog", "Bird", "Hamster" };
                public int getSize() { return strings.length; }
                public Object getElementAt(int i) { return strings[i]; }
            });
            listSelect.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    listSelectMouseClicked(evt);
                }
            });
            jScrollPane1.setViewportView(listSelect);

            txtList.setColumns(12);
            txtList.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N
            txtList.setLineWrap(true);
            txtList.setRows(12);
            txtList.setAutoscrolls(false);
            txtList.setFocusable(false);
            jScrollPane2.setViewportView(txtList);

            lblWaitput.setText("60");
            lblWaitput.setToolTipText("Input wait time here.");

            jLabel1.setText("Wait Time:");

            btnStart.setText("Start The Show");
            btnStart.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnStartActionPerformed(evt);
                }
            });

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(lblWaitput, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 88, Short.MAX_VALUE)
                            .addComponent(btnStart))
                        .addComponent(lblDisplay, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(lblWaitput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabel1)
                                .addComponent(btnStart))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(lblDisplay, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jScrollPane1)
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 251, Short.MAX_VALUE))
                            .addGap(0, 0, Short.MAX_VALUE)))
                    .addContainerGap())
            );

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

        private void listSelectMouseClicked(java.awt.event.MouseEvent evt) {                                        

            txtList.setText(txtList.getText()  + options[listSelect.getSelectedIndex()] + " ");

            // TODO add your handling code here:
        }                                       

        private void btnStartActionPerformed(java.awt.event.ActionEvent evt) {                                         
                    Timer time = new Timer(waitTime, TimePANG);
                    time.start();

            // END OF SLIDES NOTHING FURTHER
        }                                        


        /**
         * @param args the command line arguments
         */
        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 ex) {
                java.util.logging.Logger.getLogger(MainSlides.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(MainSlides.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(MainSlides.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(MainSlides.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>

            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MainSlides().setVisible(true);
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton btnStart;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JScrollPane jScrollPane2;
        private javax.swing.JLabel lblDisplay;
        private javax.swing.JTextField lblWaitput;
        private javax.swing.JList listSelect;
        private javax.swing.JTextArea txtList;
        // End of variables declaration                   

    }
1
  • Can you clarify the specific problem you are having? Commented Dec 20, 2016 at 18:06

1 Answer 1

2

The point of using a Timer is to get rid of all your loops.

You have an array of objects, so you also need an index of to track which object is currently being displayed.

So when you click on the button all you do is start the Timer and then the ActionListener will display the object based on the current index.

So the code in the ActionListener of your "Start" button might look something like:

ActionListener al = new ActionListener()
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
        String fileName = "..." + selects[selectIndex] + ".jpg";
        Icon icon = new ImageIcon( filename );
        label.setIcon( icon );
        selectIndex++;

        if (selectIndex) > selects.length)
            selectIndex = 0;
    }
};

...

Timer timer = new Timer(waitTime, al);
timer.start();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.